﻿
using Futajma.MigrationStudio.CommonLib.TreeDebug;
using Futajma.MigrationStudio.DataDefinition;
using Futajma.MigrationStudio.FileSystemPersistence;
using Futajma.MigrationStudio.GenericImporter;
using Futajma.MigrationStudio.GenericPersistance;
using LLTreeManagementApplication.Configuration;
using LLTreeManagementApplication.Data;
using LLTreeManagementApplication.Dialog;
using LLTreeManagementApplication.InfoMessage;
using LLTreeManagementApplication.Utils;
using Futajma.MigrationStudio.SharePointPersistance;
using Futajma.MigrationStudio.SharePointPersistance.Dialog;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Futajma.MigrationStudio.CommonLib;
using Futajma.MigrationStudio.SharePointPersistence;
using Futajma.MigrationStudio.ApplicationUpdate;
using Futajma.MigrationStudio.CommonLib.TreeOperations;
using Futajma.MigrationStudio.GenericPersistance.Data;
using Futajma.MigrationStudio.Configuration;

namespace LLTreeManagementApplication
{
    public partial class MainWindow : Form
    {

        #region MemberVariables, Const and Properties
        private ContextMenuStrip _siteMenu, _libraryMenu, _folderMenu, _siteCollectionMenu, _applicationMenu;
        string _projectFileName = "";

        InfoMessageHandler _infoMessageHandler = null;

        //ActionItemHandler _exportHandler = new ActionItemHandler();
        //GovernanceData _governanceData = new GovernanceData();
        ProjectData _projectData = new ProjectData(new GovernanceData(true), new ProjectParameter(), ImporterLoader.GetImporter());
        ITemplateStructureLoader _templateStructureLoader = new SharePoint2010TemplateStructureLoader();

        SharePointStructureValidation _sharePointStructureValidation = new SharePointStructureValidation();
        //int _selectedSharePointItemId = -1;
        //int _currentProjectVersion = 0;
        //IImporter _sourceImporter = new LiveLinkFileImporter();

        ProgressScreen _progressScreen = new ProgressScreen();

        TreeNodeDebugger _treeNodeDebugger = new TreeNodeDebugger();
        ApplicationUpdater _applicationUpdater = null;

        bool _isUserInMigrationTeamGroup = false;
        bool _isUserInMigrationTeamGroupNotConfirmed = false;

        bool _extendedLogging = false;

        #endregion

        #region Constructor
        public MainWindow()
        {
            bool.TryParse(ConfigurationManager.AppSettings["EnableExtendedLogging"], out _extendedLogging);

            InitializeComponent();
        }
        #endregion

        #region Init
        private void MainWindow_Load(object sender, EventArgs e)
        {

            #region Preset Menu view
#if DEBUG
            toolStripMenuItem2.Visible = true;
#else
            toolStripMenuItem2.Visible = false;
#endif

            #endregion

            var splashScreen = new Dialog.SplashScreen();
            splashScreen.CenterForm(this).Show();
            splashScreen.Refresh();

            _infoMessageHandler = new InfoMessageHandler(lbxOutput, _extendedLogging);

            //_projectData.ActionItemHandler.ExportHandlerInformationUpdate += exportHandlerInformationUpdate;

            _projectData.Importer.ProgressInit += ProgressInit;
            _projectData.Importer.ProgressUpdate += ProgressUpdate;

            LoadConfiguration();

            InitMenu();

            // no smaller than design time size
            this.MinimumSize = new System.Drawing.Size(this.Width, this.Height);
            this.Text = string.Format("{0} -- Migration Studio",  ConfigurationManager.AppSettings["ProjectTitle"]);

            #region Load Tree Images
            targetTreeView.ImageList = TreeImageUtils.GetTreeImageList();
            #endregion

            #region Build Trees
            //mainTree.Nodes.Clear();
            //var rootNode = new TreeNode("LiveLink tree", 2, 2);
            //DataNode dataNodeLL = new DataNode() { Title = "LiveLink tree", LiveLinkType = 0 };
            //rootNode.Tag = dataNodeLL;
            //mainTree.Nodes.Add(rootNode);

            //var spRootNode = new TreeNode("SharePoint");
            //DataNode dataNodeSP = new DataNode() { Title = "LiveLink tree"/*, SourceParentNode = null*/, LiveLinkType = LiveLinkType.NotDefined, SharePointType = SharePointType.Application };
            //spRootNode.Tag = dataNodeSP;
            //spRootNode.ContextMenuStrip = _applicationMenu;
            //spTreeView.Nodes.Add(spRootNode);
            CreateSPTreeViewRoot(0);
            #endregion

            #region Register Eventhandler
            targetTreeView.KeyDown += spTreeView_KeyDown;
            sourceTreeView.ItemDrag += treeView_ItemDrag;
            sourceTreeView.NodeMouseClick += mainTree_NodeMouseClick;
            targetTreeView.ItemDrag += spTreeView_ItemDrag;
            targetTreeView.DragEnter += treeView_DragEnter;
            targetTreeView.DragEnter += treeView_DragEnter;
            targetTreeView.DragDrop += spTreeView_DragDrop;
            targetTreeView.DragOver += spTreeView_DragOver;
            targetTreeView.NodeMouseClick += spTreeView_NodeMouseClick;

            #endregion

            splashScreen.Dispose();

        }

        private void LoadConfiguration()
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                _infoMessageHandler.ExtendedLogging("Start loading governance");
                _projectData.GovernanceData = SharePoint2010ApplicationConfiguration.LoadGovernanceData();

                if (_projectData.GovernanceData == null)
                {
                    _infoMessageHandler.PrintInfo("Governance data not loaded, use project rules");
                    _projectData.GovernanceData = new GovernanceData(true);
                }
                else
                {
                    _infoMessageHandler.ExtendedLogging("Start loading governance done");
                }
            }
            catch (Exception ex)
            {
                _infoMessageHandler.PrintError(ex.Message);
                publishToDashboardToolStripMenuItem.Enabled = false;
                openFromDashboardToolStripMenuItem.Enabled = false;
                importFromDashboardToolStripMenuItem.Enabled = false;
                toolStripMenuItemReloadGovernanceDefinition.Enabled = false;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }

            try
            {
                Cursor.Current = Cursors.WaitCursor;
                _infoMessageHandler.ExtendedLogging("Start loading template structure");
                if (!_templateStructureLoader.LoadDefinition(null))
                {
                    _infoMessageHandler.PrintInfo("Template structure data not loaded, use project structure");
                    _templateStructureLoader.BuildDefaultDefinition();
                }
                else
                {
                    _infoMessageHandler.ExtendedLogging("Start loading template structure done");
                }
            }
            catch (Exception ex)
            {
                _infoMessageHandler.PrintError(ex.Message);
                _templateStructureLoader.BuildDefaultDefinition();
                publishToDashboardToolStripMenuItem.Enabled = false;
                openFromDashboardToolStripMenuItem.Enabled = false;
                importFromDashboardToolStripMenuItem.Enabled = false;
                toolStripMenuItemReloadGovernanceDefinition.Enabled = false;

            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }

            try
            {

#if DEBUG
                _isUserInMigrationTeamGroup = true;
#endif

                Cursor.Current = Cursors.WaitCursor;
                SharePoint2010Persistence pers = new SharePoint2010Persistence();
                _infoMessageHandler.ExtendedLogging("Start check use is in migration team");
#if DEBUG
                bool isUserInMigrationTeam = true;
#else

                bool isUserInMigrationTeam = pers.EnsureUserInMigrationTeamGroup(CredentialManager.ToString());
                //bool isUserInMigrationTeam = pers.EnsureUserInMigrationTeamGroup(WindowsIdentity.GetCurrent().Name);
#endif
                _infoMessageHandler.ExtendedLogging("Start check use is in migration team done");
                _isUserInMigrationTeamGroup = isUserInMigrationTeam;
                _isUserInMigrationTeamGroupNotConfirmed = false;
                
            }
            catch (Exception ex)
            {
                _infoMessageHandler.ExtendedLogging("Start check use is in migration team exception");
                _infoMessageHandler.ExtendedLogging(ex.Message);
#if DEBUG
#else
                _isUserInMigrationTeamGroup = false;
                _isUserInMigrationTeamGroupNotConfirmed = true;
#endif
            }
            finally
            {
                Cursor.Current = Cursors.Default;
                // whole util menu 
                toolStripMenuUtils.Visible = toolStripMenuUtils.Enabled = _isUserInMigrationTeamGroup;
                // import menu items
                importToolStripMenuItem.Enabled = importToolStripMenuItem.Visible = _isUserInMigrationTeamGroup || _isUserInMigrationTeamGroupNotConfirmed;
                importFromDashboardToolStripMenuItem.Enabled = importFromDashboardToolStripMenuItem.Visible = _isUserInMigrationTeamGroup;
                //openFromDashboardToolStripMenuItem.Enabled = openFromDashboardToolStripMenuItem.Visible = _isUserInMigrationTeamGroup;
                // Whole delta migration menu 
                deltaMigrationToolStripMenuItem.Enabled = deltaMigrationToolStripMenuItem.Visible = _isUserInMigrationTeamGroup;
                _infoMessageHandler.ExtendedLogging("All menu settings done");
            }

            _infoMessageHandler.ExtendedLogging("Instantiate auto updater");
            _applicationUpdater = new ApplicationUpdater();

            try
            {
                _infoMessageHandler.ExtendedLogging("Start upload installation pending reports");
                _applicationUpdater.UploadInstallationReports();
                _infoMessageHandler.ExtendedLogging("Start upload installation pending reports done ");
                _infoMessageHandler.ExtendedLogging(string.Format("Check for pending updates, is user in migration group = {0}", _isUserInMigrationTeamGroup));
                if (_applicationUpdater.CheckForUpdates(_isUserInMigrationTeamGroup ? TargetAudience.MigrationConsultant : TargetAudience.ContentOwner))
                {
                    DialogResult dr = MessageBox.Show("A new update is available.\nPress \"Yes\" to start the update and wait some moments for next instructions.",
                        "A new update is available.", MessageBoxButtons.YesNo);
                    if (dr == System.Windows.Forms.DialogResult.Yes)
                    {
                        _applicationUpdater.OnPrepareUpdatesCompleted += _applicationUpdater_OnPrepareUpdatesCompleted;
                        _applicationUpdater.PrepareForUpdate();
                        //Cursor.Current = Cursors.WaitCursor;
                    }
                }
            }
            catch (Exception ex)
            {
                _infoMessageHandler.ExtendedLogging("Error during update check");
                _infoMessageHandler.ExtendedLogging(ex.StackTrace);

            }
            
            lblUserName.Text = CredentialManager.ToString();

            //lblUserName.Text = WindowsIdentity.GetCurrent().Name;
        }

        void _applicationUpdater_OnPrepareUpdatesCompleted(UpdateState updateState)
        {
            _infoMessageHandler.ExtendedLogging("Async upload check done");
            if (updateState == UpdateState.Prepared)
            {
                Cursor.Current = Cursors.Default;

                DialogResult dr = MessageBox.Show("Do you wish to install them now?", "Software updates downlaoded", MessageBoxButtons.YesNo);

                if (dr == System.Windows.Forms.DialogResult.Yes)
                {
                    _applicationUpdater.InstallUpdates();
                }
            }
            else 
            {
                MessageBox.Show("An error happens during the installation. Please contact the migration team.", "Software updates error", MessageBoxButtons.OK);
            }
            
        }

        //private void exportHandlerInformationUpdate(int actionItems)
        //{
        //    lblActionSteps.Text = string.Format("Action steps : {0}", actionItems);
        //}
        #endregion

        #region TreeSelection Events
        private void mainTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            targetTreeView.SelectedNode = e.Node;
            var data = e.Node.Tag as DataNode;

            FillDataView(e.Node, true);

            if (data != null && data.NodeDisabled && debugInformationTreeMenuItem.Checked)
            {
                _treeNodeDebugger.SelectItemAndExpandTree(e.Node, targetTreeView);
            }
        }

        void spTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            targetTreeView.SelectedNode = e.Node;
            FillDataView(e.Node, e.Node.Parent == null);

            if (debugInformationTreeMenuItem.Checked)
            {
                _treeNodeDebugger.SelectItemAndExpandTree(e.Node, sourceTreeView);
            }
        }

        void spTreeView_DragOver(object sender, DragEventArgs e)
        {

            targetTreeView.Scroll();
            // Retrieve the client coordinates of the mouse position.
            Point targetPoint = targetTreeView.PointToClient(new Point(e.X, e.Y));

            // Select the node at the mouse position.
            targetTreeView.SelectedNode = targetTreeView.GetNodeAt(targetPoint);



        }

        #endregion

        #region Private Methods
        private void FillDataView(TreeNode node, bool notEditable = false)
        {
            lbInfoMessages.Items.Clear();
            txtSourcePath.Text = string.Empty;

            if (node != null)
            {
                DataNode dataNode = node.Tag as DataNode;
                if (dataNode != null)
                {
                    DataNode parentDataNode = null;

                    if (node.Parent != null)
                    {
                        parentDataNode = node.Parent.Tag as DataNode;
                    }

                    lbInfoMessages.Items.Add(string.Format("{0} : {1}", "NodeSize", DataComplexityCalculation.ToFuzzyByteString(dataNode.NodeSize)));
                    lbInfoMessages.Items.Add(string.Format("{0} : {1}", "NodeCount", dataNode.NodeCount));
                    lbInfoMessages.Items.Add(string.Format("{0} : {1}", "FileSize", DataComplexityCalculation.ToFuzzyByteString(dataNode.FileSize)));
                    txtSourcePath.Text = dataNode.SourcePath;
                    //lbInfoMessages.Items.Add(string.Format("{0} : {1}", "SourcePath", dataNode.SourcePath));

                    #region TemplateDefinition View

                    if (dataNode.SharePointType == SharePointType.SiteCollection ||
                        dataNode.SharePointType == SharePointType.Site ||
                        dataNode.SharePointType == SharePointType.DocLibrary)
                    {
                        var template = TemplateDefinition.Instance.GetTemplate(dataNode.TemplateId);

                        if (template != null)
                        {
                            lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Template-Name", template.Name));
                        }
                    }


                    #endregion


                    if ((dataNode.ViolationType & ViolationType.ItemSizeExceeded) != 0)
                    {
                        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Violation", "Item Size exceeded."));
                    }

                    if ((dataNode.ViolationType & ViolationType.ItemThresholdExceeded) != 0)
                    {
                        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Violation", "Item threshold exceeded."));
                        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Item count", dataNode.ItemCount));
                    }

                    if ((dataNode.ViolationType & ViolationType.PathLengthExceeded) != 0)
                    {
                        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Violation", string.Format("Path length more than {0} chars.", _projectData.GovernanceData.PathLenghtLimit)));
                        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Pathlength", dataNode.PathLength));
                    }

                    if ((dataNode.ViolationType & ViolationType.FileNameDuplicated) != 0)
                    {
                        lbInfoMessages.Items.Add(string.Format("Violation : {0} files with the identical path.", dataNode.DuplicatedFilenameViolationCount));
                    }

                    if ((dataNode.ViolationType & ViolationType.FilePathNameLengthExceeds) != 0)
                    {
                        lbInfoMessages.Items.Add(string.Format("Violation: Filename exceeds with {0} chars the 128 char limit.", dataNode.EncodedTitle.Length));
                    }

                    if ((dataNode.ViolationType & ViolationType.IllegalFileExtensionDetected) != 0)
                    {
                        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Violation", "File with this extension are restricted."));
                    }

                    if ((dataNode.ViolationType & ViolationType.IllegalFileAndFolderCharacterDetected) != 0 ||
                        (dataNode.ViolationType & ViolationType.IllegalSiteAndSubsiteCharacterDetected) != 0)
                    {
                        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Violation", "Contains unsupported characters in path or name."));
                    }


                    //switch (dataNode.ViolationType)
                    //{
                    //    case ViolationType.ItemSizeExceeded:
                    //        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Violation", dataNode.ViolationType));
                    //        break;
                    //    case ViolationType.ItemThresholdExceeded:
                    //        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Violation", dataNode.ViolationType));
                    //        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Pathlength", dataNode.ItemCount));
                    //        break;
                    //    case ViolationType.PathLengthExceeded:
                    //        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Violation", dataNode.ViolationType));
                    //        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Pathlength", dataNode.PathLength));
                    //        break;
                    //    case ViolationType.FileNameDuplicated:
                    //        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Violation", dataNode.ViolationType));
                    //        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Filenames with same path", dataNode.DuplicatedFilenameViolationCount));
                    //        break;
                    //    case ViolationType.FilePathNameLengthExceeds:
                    //        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Violation", dataNode.ViolationType));
                    //        //lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Filenames with same path", dataNode.DuplicatedFilenameViolationCount));
                    //        break;
                    //    case ViolationType.ForbiddenFileExtensionDetected:
                    //        lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Violation", dataNode.ViolationType));
                    //        //lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Filenames with same path", dataNode.DuplicatedFilenameViolationCount));
                    //        break;


                    //}

                    //lbInfoMessages.Items.Add(string.Format("{0} : {1}", "ItemCount", dataNode.ItemCount));

                    //lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Libraries with Threshold exceeded", dataNode.ItemThresholdExceededCount));
                    //lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Files with size exceeded", dataNode.ItemSizeExceededCount));

                    txtItemTitle.Text = dataNode.Title;
                    txtItemName.Text = dataNode.TargetPath;
                    txtItemTitle.Enabled = _projectData.GovernanceData.IsTitleEditEnabled(dataNode);
                    txtItemName.Enabled = _projectData.GovernanceData.IsNameEditEnabled(dataNode);
                    btnApproveItemChanges.Enabled = txtItemTitle.Enabled || txtItemName.Enabled;

                    //if (dataNode.SharePointType == SharePointType.SiteCollection)
                    //{
                    //    lbInfoMessages.Items.Add(string.Format("{0} : {1}", "Url", dataNode.TargetPath));
                    //}

                    cbxRemoveFolderStructure.Enabled = dataNode.SharePointType == SharePointType.DocLibrary;

                    if (dataNode.SharePointType == SharePointType.DocLibrary)
                    {
                        cbxRemoveFolderStructure.Checked = dataNode.RemoveFolderStructure;
                    }
                    else
                    {
                        cbxRemoveFolderStructure.Checked = false;
                    }

                }
            }

            if (notEditable)
            {
                btnApproveItemChanges.Enabled = txtItemTitle.Enabled = txtItemName.Enabled = false;
            }
        }

        TreeNode CreateSPTreeViewRoot(int projectVersion)
        {
            var spRootNode = new TreeNode(ConfigurationManager.AppSettings["TargetTreeRootTitle"]);
            DataNode dataNodeSP = _projectData.Importer.GetNewDataNode(projectVersion);
            dataNodeSP.Title = "Target Tree";
            dataNodeSP.SharePointType = SharePointType.Application;
            //DataNode dataNodeSP = new DataNode() { Title = "Target Tree"/*, SourceParentNode = null*/, SharePointType = SharePointType.Application };
            spRootNode.Tag = dataNodeSP;
            spRootNode.ContextMenuStrip = _applicationMenu;
            targetTreeView.Nodes.Add(spRootNode);
            return spRootNode;
        }
        #endregion

        #region MenuStrip
        private void InitMenu()
        {

            commitMappingToolStripMenuItem.Enabled = false;
            tspImportDeploymentReport.Enabled = false;

            loadDeltaMigrationFromMenuItemDashboardToolStrip.Enabled = false;
            toolStripMenuItemLoadDeltaMigration.Enabled = false;

            // Create the ContextMenuStrip.
            _siteMenu = new ContextMenuStrip();
            _libraryMenu = new ContextMenuStrip();
            _folderMenu = new ContextMenuStrip();
            _siteCollectionMenu = new ContextMenuStrip();
            _applicationMenu = new ContextMenuStrip();

            #region SiteMenu Strip
            //Create some menu items.
            ToolStripMenuItem siteMenu1 = new ToolStripMenuItem();
            siteMenu1.Text = "Convert to Library";
            siteMenu1.Click += siteMenu1_Click;

            ToolStripMenuItem siteMenu2 = new ToolStripMenuItem();
            siteMenu2.Text = "Add new Library";
            siteMenu2.Click += siteMenu2_Click;

            ToolStripMenuItem siteMenu3 = new ToolStripMenuItem();
            siteMenu3.Text = "Delete Site";
            siteMenu3.Click += siteMenu3_Click;
            siteMenu3.Visible = false;

            _siteMenu.Opening += _siteMenu_Opening;
            _siteMenu.Items.Add(siteMenu1);
            _siteMenu.Items.Add(siteMenu2);
            _siteMenu.Items.Add(siteMenu3);
            #endregion

            #region Library Menu
            ToolStripMenuItem libMenu1 = new ToolStripMenuItem();
            libMenu1.Text = "Convert to Site";
            libMenu1.Click += libMenu1_Click;

            ToolStripMenuItem libMenu2 = new ToolStripMenuItem();
            libMenu2.Text = "Add new Folder";
            libMenu2.Click += libMenu2_Click;

            ToolStripMenuItem libMenu3 = new ToolStripMenuItem();
            libMenu3.Text = "Delete Library";
            libMenu3.Click += libMenu3_Click;
            libMenu3.Visible = false;

            _libraryMenu.Opening += _libraryMenu_Opening;
            _libraryMenu.Items.Add(libMenu1);
            _libraryMenu.Items.Add(libMenu2);
            _libraryMenu.Items.Add(libMenu3);

            DynamicMenuOperations.CreateSearchAndReplaceToolStripMenuItem(_libraryMenu, searchAndReplaceExportDialog_Click, !_projectData.ProjectParameter.ProjectIsCommited);

            #endregion

            #region Folder Menu

            ToolStripMenuItem folderMenu1 = new ToolStripMenuItem();
            folderMenu1.Text = "Add new Folder";
            folderMenu1.Click += folderMenu1_Click;

            ToolStripMenuItem folderMenu2 = new ToolStripMenuItem();
            folderMenu2.Text = "Delete Folder";
            folderMenu2.Click += folderMenu2_Click;
            folderMenu2.Visible = false;

            _folderMenu.Items.Add(folderMenu1);
            _folderMenu.Items.Add(folderMenu2);

            _folderMenu.Opening += _folderMenu_Opening;

            DynamicMenuOperations.CreateSearchAndReplaceToolStripMenuItem(_folderMenu, searchAndReplaceExportDialog_Click, !_projectData.ProjectParameter.ProjectIsCommited);

            #endregion

            #region SiteCollection Menu
            ToolStripMenuItem scMenu1 = new ToolStripMenuItem();
            scMenu1.Text = "New Site";
            scMenu1.Click += scMenu1_Click;

            ToolStripMenuItem scMenu3 = new ToolStripMenuItem();
            scMenu3.Text = "New library";
            scMenu3.Click += scMenu3_Click;

            ToolStripMenuItem scMenu2 = new ToolStripMenuItem();
            scMenu2.Text = "Delete Site Collection";
            scMenu2.Click += scMenu2_Click;
            scMenu2.Visible = false;

            _siteCollectionMenu.Opening += _siteCollectionMenu_Opening;
            _siteCollectionMenu.Items.Add(scMenu1);
            _siteCollectionMenu.Items.Add(scMenu3);
            _siteCollectionMenu.Items.Add(scMenu2);
            #endregion

            #region Application Menu
            CreateApplicationDynamicMenu();
            #endregion

            #region Set Dynamic Menu item text
            governanceCheckToolStripMenuItem.Text = string.Format("{0} Governance Validation", ConfigurationManager.AppSettings["TargetTreeRootTitle"]);
            runDataValidationToolStripMenuItem.Text = string.Format("{0} Structure Validation", ConfigurationManager.AppSettings["TargetTreeRootTitle"]);
            #endregion

            #region Dynamic Exporter Menu
            foreach (IExporter exporter in ExporterLoader.GetExporterList())
            {                
                var child = new ToolStripMenuItem(exporter.GetName());
                child.Tag = exporter;
                child.Click += exporter_Click;
                tspDynamicExporterSelection.DropDownItems.Add(child);
            }
            #endregion
        }

        #region Dynamic Exporter Menu Event
        private void exporter_Click(object sender, EventArgs e)
        {
            var item = sender as ToolStripMenuItem;
            var exporter = item.Tag as IExporter;

            exporter.ShowDialog(_projectData.ProjectParameter, targetTreeView);

            UpdateMenuItems();
        }
        #endregion

        void _siteCollectionMenu_Opening(object sender, CancelEventArgs e)
        {
            ContextMenuStrip menu = sender as ContextMenuStrip;
            SetToolStripMenuItemVisability(menu, 2);
        }

        void _siteMenu_Opening(object sender, CancelEventArgs e)
        {
            ContextMenuStrip menu = sender as ContextMenuStrip;
            SetToolStripMenuItemVisability(menu, 2);
        }

        void _libraryMenu_Opening(object sender, CancelEventArgs e)
        {
            ContextMenuStrip menu = sender as ContextMenuStrip;
            SetToolStripMenuItemVisability(menu, 2);
        }

        void _folderMenu_Opening(object sender, CancelEventArgs e)
        {
            ContextMenuStrip menu = sender as ContextMenuStrip;
            SetToolStripMenuItemVisability(menu, 1);
        }

        private void SetToolStripMenuItemVisability(System.Windows.Forms.ContextMenuStrip menu, int menuItemIndex)
        {
            if (menu != null)
            {
                var hitTest = targetTreeView.HitTest(targetTreeView.PointToClient(new Point(menu.Left, menu.Top)));
                if (hitTest.Node != null)
                {
                    DataNode dataNode = hitTest.Node.Tag as DataNode;

                    //if (dataNode != null && dataNode.Deletable)
                    //{
                    //    menu.Items[menuItemIndex].Visible = true;
                    //}
                    //else
                    //{
                    menu.Items[menuItemIndex].Visible = false;
                    //}
                }
                else
                {
                    menu.Items[menuItemIndex].Visible = false;
                }
            }
        }

        // add new library
        private void scMenu3_Click(object sender, EventArgs e)
        {
            TreeNode node = CreateNewNode(SharePointType.DocLibrary, "New Library", _libraryMenu);
            targetTreeView.SelectedNode.Nodes.Add(node);
            //_projectData.ActionItemHandler.InsertAction(node);
        }

        // delete folder
        private void folderMenu2_Click(object sender, EventArgs e)
        {
            RejectTreeNode(targetTreeView.SelectedNode);
            //            DeleteSelectedNode();
        }

        // add new folder
        private void folderMenu1_Click(object sender, EventArgs e)
        {
            TreeNode node = CreateNewNode(SharePointType.Folder, "New Folder", _folderMenu);
            targetTreeView.SelectedNode.Nodes.Add(node);
            //_projectData.ActionItemHandler.InsertAction(node);
        }

        // delete selected library
        private void libMenu3_Click(object sender, EventArgs e)
        {
            RejectTreeNode(targetTreeView.SelectedNode);
            //DeleteSelectedNode();
        }

        // add new folder
        private void libMenu2_Click(object sender, EventArgs e)
        {
            TreeNode node = CreateNewNode(SharePointType.Folder, "New Folder", _folderMenu);
            targetTreeView.SelectedNode.Nodes.Add(node);
            //_projectData.ActionItemHandler.InsertAction(node);
        }

        // convert library to site
        private void libMenu1_Click(object sender, EventArgs e)
        {
            TreeNode node = targetTreeView.SelectedNode;

            DataNode data = node.Tag as DataNode;

            //_projectData.ActionItemHandler.ConvertNode(node, SharePointType.Site);
            data.SharePointType = SharePointType.Site;
            node.SelectedImageIndex = node.ImageIndex = TreeImageUtils.GetIconIndex(SharePointType.Site);

            node.SelectedImageIndex = TreeImageUtils.CalculateImageIndex(node, _projectData.ProjectParameter.ProjectVersion);
            node.SelectedImageIndex = TreeImageUtils.CalculateImageIndex(node, _projectData.ProjectParameter.ProjectVersion);

            node.ContextMenuStrip = _siteMenu;

            foreach (TreeNode childNode in node.Nodes)
            {
                RecalculateNode(childNode, node, true);
            }
        }

        // add new site
        private void scMenu1_Click(object sender, EventArgs e)
        {
            TreeNode node = CreateNewNode(SharePointType.Site, "New Site", _siteMenu);
            targetTreeView.SelectedNode.Nodes.Add(node);
            //_projectData.ActionItemHandler.InsertAction(node);
        }

        // delete selected site collection
        private void scMenu2_Click(object sender, EventArgs e)
        {
            //DeleteSelectedNode();
            RejectTreeNode(targetTreeView.SelectedNode);
        }

        private void DeleteSelectedNode()
        {
            RejectTreeNode(targetTreeView.SelectedNode);
        }
        // opens site colletion set dialog
        private void urlDialog_Click(object sender, EventArgs e)
        {
            TreeNode node = targetTreeView.SelectedNode;

            DataNode data = node.Tag as DataNode;

            if (data != null && data.SharePointType == SharePointType.SiteCollection)
            {
                var dlg = new SetSiteCollectionUrl();
                dlg.SiteColelctionUrl = data.TargetPath;

                if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    data.TargetPath = dlg.SiteColelctionUrl;
                }
            }

        }

        #region Dynamic Menus
        // add new site collection
        private void appMenu1_Click(object sender, EventArgs e)
        {
            var scDefId = (Guid)((ToolStripMenuItem)sender).Tag;

            SiteCollectionTemplate scDef = TemplateDefinition.Instance.GetTemplate(scDefId) as SiteCollectionTemplate;

            if (scDef != null)
            {
                TreeNode node = CreateNewNode(SharePointType.SiteCollection, scDef.Name, CreateDynamicSiteCollectionMenu(scDef), scDef);
                targetTreeView.SelectedNode.Nodes.Add(node);

                CreateRootSiteFromTemplateDefinition(scDef.RootSiteTemplate, node);

                CreateSitesFromTemplateDefinition(scDef, node);

                //_projectData.ActionItemHandler.InsertAction(node);
            }
        }

        private void dynamicMenu_NewLibrary_Click(object sender, EventArgs e)
        {
            var libTemplateDefId = (Guid)((ToolStripMenuItem)sender).Tag;

            LibraryTemplate libTemplateDef = TemplateDefinition.Instance.GetTemplate(libTemplateDefId) as LibraryTemplate;

            if (libTemplateDef != null)
            {
                var contextStrip = DynamicMenuOperations.CreateDynamicLibraryMenu(libTemplateDef, libMenu2_Click, libMenu3_Click);

                TreeNode node = CreateNewNode(SharePointType.DocLibrary, libTemplateDef.Name, contextStrip, libTemplateDef);
                targetTreeView.SelectedNode.Nodes.Add(node);
                //_projectData.ActionItemHandler.InsertAction(node);
                DynamicMenuOperations.CreateSearchAndReplaceToolStripMenuItem(contextStrip, searchAndReplaceExportDialog_Click, !_projectData.ProjectParameter.ProjectIsCommited);                 
                CreateFolderFromTemplateDefinition(libTemplateDef, node);
            }
        }

        private void dynamicMenu_NewSite_Click(object sender, EventArgs e)
        {
            var siteTemplateDefId = (Guid)((ToolStripMenuItem)sender).Tag;

            SiteTemplate siteTemplateDef = TemplateDefinition.Instance.GetTemplate(siteTemplateDefId) as SiteTemplate;

            if (siteTemplateDef != null)
            {
                var contextStrip = CreateDynamicSiteMenu(siteTemplateDef);

                TreeNode node = CreateNewNode(SharePointType.Site, siteTemplateDef.Name, contextStrip, siteTemplateDef);
                targetTreeView.SelectedNode.Nodes.Add(node);
                CreateListFromTemplateDefinition(siteTemplateDef, node);
                //_projectData.ActionItemHandler.InsertAction(node);
            }
        }

        private void CreateApplicationDynamicMenu()
        {
            ToolStripMenuItem appMenu1 = new ToolStripMenuItem();
            appMenu1.Text = "New Site Collection";

            _applicationMenu.Items.Clear();

            _applicationMenu.Items.Add(appMenu1);

            foreach (var scDef in TemplateDefinition.Instance.SiteCollectionDefinitions)
            {
                ToolStripMenuItem subItem = new ToolStripMenuItem();
                subItem.Text = scDef.Name;
                subItem.Tag = scDef.ID;
                subItem.Click += appMenu1_Click;
                appMenu1.DropDownItems.Add(subItem);
            }

            DynamicMenuOperations.CreateSearchAndReplaceToolStripMenuItem(_applicationMenu, searchAndReplaceExportDialog_Click, !_projectData.ProjectParameter.ProjectIsCommited);
            CreateRedirectorExportToolStripMenuItem(_applicationMenu);
            ToolStripSeparator separator = new ToolStripSeparator();
            _applicationMenu.Items.Add(separator);
            CreateSortTreeOrderToolStripMenuItem(_applicationMenu);
        }

        //private ContextMenuStrip CreateDynamicLibraryMenu(LibraryTemplate libTemplateDef)
        //{
        //    var contextStrip = new ContextMenuStrip();

        //    ToolStripMenuItem libMenu2 = new ToolStripMenuItem();
        //    libMenu2.Text = "Add new Folder";
        //    libMenu2.Enabled = libTemplateDef.CreateFolderAllowed;
        //    libMenu2.Click += libMenu2_Click;
        //    contextStrip.Items.Add(libMenu2);

        //    ToolStripMenuItem libMenu3 = new ToolStripMenuItem();
        //    libMenu3.Text = "Delete Library";
        //    libMenu3.Click += libMenu3_Click;
        //    contextStrip.Items.Add(libMenu3);
        //    return contextStrip;
        //}

        private ContextMenuStrip CreateDynamicSiteCollectionMenu(SiteCollectionTemplate siteCollectionDefinition)
        {
            var contextStrip = new ContextMenuStrip();

            #region dynamics Library Menu
            ToolStripMenuItem libMenu = new ToolStripMenuItem();
            libMenu.Text = "Add new Library";
            libMenu.Enabled = siteCollectionDefinition.RootSiteTemplate.LibraryTemplates.Where(p => p.NotShownAsCreateNewLibrary == false).ToArray().Length > 0 ? true : false;

            foreach (var library in siteCollectionDefinition.RootSiteTemplate.LibraryTemplates.Where(p => p.NotShownAsCreateNewLibrary == false))
            {
                ToolStripMenuItem subItem = new ToolStripMenuItem();
                subItem.Text = library.Name;
                subItem.Tag = library.ID;
                subItem.Click += dynamicMenu_NewLibrary_Click;
                libMenu.DropDownItems.Add(subItem);
            }
            contextStrip.Items.Add(libMenu);
            #endregion

            #region Dynamic Site Menu
            ToolStripMenuItem siteMenu = new ToolStripMenuItem();
            siteMenu.Text = "Add new Site";
            siteMenu.Enabled = siteCollectionDefinition.SiteTemplates.Count > 0 ? true : false;

            foreach (var site in siteCollectionDefinition.SiteTemplates)
            {
                ToolStripMenuItem subItem = new ToolStripMenuItem();
                subItem.Text = site.Name;
                subItem.Tag = site.ID;
                subItem.Click += dynamicMenu_NewSite_Click;
                siteMenu.DropDownItems.Add(subItem);
            }
            contextStrip.Items.Add(siteMenu);
            #endregion

            #region Delete Site Collection Menu
            ToolStripMenuItem scMenu2 = new ToolStripMenuItem();
            scMenu2.Text = "Delete Site Collection";
            scMenu2.Click += scMenu2_Click;
            scMenu2.Visible = true;

            contextStrip.Items.Add(scMenu2);
            #endregion

            #region Delete Site Collection Menu
            //ToolStripMenuItem urlDialog = new ToolStripMenuItem();
            //urlDialog.Text = "Set Site Collection Url";
            //urlDialog.Click += urlDialog_Click;
            //urlDialog.Visible = true;

            //contextStrip.Items.Add(urlDialog);
            DynamicMenuOperations.CreateSearchAndReplaceToolStripMenuItem(contextStrip, searchAndReplaceExportDialog_Click, !_projectData.ProjectParameter.ProjectIsCommited);
            CreateRedirectorExportToolStripMenuItem(contextStrip);
            
            #endregion

            return contextStrip;
        }

        void CreateSortTreeOrderToolStripMenuItem(ContextMenuStrip parentMenu)
        {
                var menu = new ToolStripMenuItem();
                menu.Text = "Sort tree order";
                menu.Click += refreshTree;
                menu.Visible = true;

                parentMenu.Items.Add(menu);
        }

        private void refreshTree(object sender, EventArgs e)
        {
            targetTreeView.Sort();
        }

        void CreateRedirectorExportToolStripMenuItem(ContextMenuStrip menu)
        {
            if (_isUserInMigrationTeamGroup)
            {
                ToolStripMenuItem redirectorExportDialog = new ToolStripMenuItem();
                redirectorExportDialog.Text = "Redirector Export";
                redirectorExportDialog.Click += redirectorExportDialog_Click;
                redirectorExportDialog.Visible = true;

                menu.Items.Add(redirectorExportDialog);
            }
        }

        //void CreateSearchAndReplaceToolStripMenuItem(ContextMenuStrip menu)
        //{
        //    ToolStripMenuItem searchAndReplaceDialog = new ToolStripMenuItem();
        //    searchAndReplaceDialog.Text = "Search And Replace";
        //    searchAndReplaceDialog.Click += searchAndReplaceExportDialog_Click;
        //    searchAndReplaceDialog.Visible = true;

        //    menu.Items.Add(searchAndReplaceDialog);
        //}

        private void searchAndReplaceExportDialog_Click(object sender, EventArgs e)
        {
            _projectData.GovernanceData.ShowSearchAndReplaceDialog(targetTreeView.SelectedNode);
        }

        void redirectorExportDialog_Click(object sender, EventArgs e)
        {
            var dlg = new RedirectorExport(targetTreeView.SelectedNode);
            dlg.CenterForm(this).ShowDialog();

        }

        private void CreateSitesFromTemplateDefinition(SiteCollectionTemplate scDef, TreeNode node)
        {
            foreach (var site in scDef.SiteTemplates)
            {
                if (site.CreateAsDefault)
                {
                    TreeNode subNode = CreateNewNode(SharePointType.Site, site.Name, CreateDynamicSiteMenu(site), site);
                    node.Nodes.Add(subNode);
                    CreateListFromTemplateDefinition(site, subNode);
                }
            }
        }

        private ContextMenuStrip CreateDynamicSiteMenu(SiteTemplate site)
        {
            var contextStrip = new ContextMenuStrip();

            //Create some menu items.
            #region Convert Site Menu
            //ToolStripMenuItem siteMenu1 = new ToolStripMenuItem();
            //siteMenu1.Text = "Convert to Library";
            //siteMenu1.Click += siteMenu1_Click;
            //siteMenu1.Enabled = site.Convertable;
            //contextStrip.Items.Add(siteMenu1);
            #endregion

            #region Dynamic Library Menu
            ToolStripMenuItem siteMenu2 = new ToolStripMenuItem();
            siteMenu2.Text = "Add new Library";
            //siteMenu2.Click += siteMenu2_Click;
            siteMenu2.Enabled = site.LibraryTemplates.Where(p => p.NotShownAsCreateNewLibrary == false).ToArray().Length > 0 ? true : false;

            foreach (var library in site.LibraryTemplates.Where(p => p.NotShownAsCreateNewLibrary == false))
            {
                ToolStripMenuItem subItem = new ToolStripMenuItem();
                subItem.Text = library.Name;
                subItem.Tag = library.ID;
                subItem.Click += dynamicMenu_NewLibrary_Click;
                siteMenu2.DropDownItems.Add(subItem);
            }
            contextStrip.Items.Add(siteMenu2);
            #endregion

            #region Dynamic Site Menu
            ToolStripMenuItem siteMenu = new ToolStripMenuItem();
            siteMenu.Text = "Add new Site";
            siteMenu.Enabled = site.SiteTemplates.Count > 0 ? true : false;
            //scMenu1.Click += scMenu1_Click;

            foreach (var subSiteDef in site.SiteTemplates)
            {
                ToolStripMenuItem subItem = new ToolStripMenuItem();
                subItem.Text = subSiteDef.Name;
                subItem.Tag = subSiteDef.ID;
                subItem.Click += dynamicMenu_NewSite_Click;
                siteMenu.DropDownItems.Add(subItem);
            }
            contextStrip.Items.Add(siteMenu);
            #endregion

            #region Delete Site Menu
            ToolStripMenuItem siteMenu3 = new ToolStripMenuItem();
            siteMenu3.Text = "Delete Site";
            siteMenu3.Click += siteMenu3_Click;
            contextStrip.Items.Add(siteMenu3);
            #endregion

            DynamicMenuOperations.CreateSearchAndReplaceToolStripMenuItem(contextStrip, searchAndReplaceExportDialog_Click, !_projectData.ProjectParameter.ProjectIsCommited);
            CreateRedirectorExportToolStripMenuItem(contextStrip);

            return contextStrip;
        }

        private void CreateFolderFromTemplateDefinition(LibraryTemplate library, TreeNode node)
        {
            if (library.Folders != null)
            {
                foreach (var folder in library.Folders)
                {
                    TreeNode subNode = CreateNewNode(SharePointType.Folder, folder.Name, _folderMenu, folder);
                    node.Nodes.Add(subNode);
                    CreateSubfolder(folder, subNode);
                }
            }
        }

        private void CreateSubfolder(Folder folder, TreeNode node)
        {
            if (folder.Folders != null)
            {
                foreach (var subFolder in folder.Folders)
                {
                    TreeNode subNode = CreateNewNode(SharePointType.Folder, subFolder.Name, _folderMenu, subFolder);
                    node.Nodes.Add(subNode);
                }
            }
        }

        private void CreateListFromTemplateDefinition(SiteTemplate site, TreeNode node)
        {
            foreach (var list in site.LibraryTemplates)
            {
                if (list.CreateAsDefault)
                {
                    var menu = DynamicMenuOperations.CreateDynamicLibraryMenu(list, libMenu2_Click, libMenu3_Click);
                    DynamicMenuOperations.CreateSearchAndReplaceToolStripMenuItem(menu, searchAndReplaceExportDialog_Click, !_projectData.ProjectParameter.ProjectIsCommited);

                    TreeNode subNode = CreateNewNode(SharePointType.DocLibrary, list.Name, menu, list);
                    node.Nodes.Add(subNode);
                    CreateFolderFromTemplateDefinition(list, subNode);
                }
            }
        }

        private void CreateRootSiteFromTemplateDefinition(SiteTemplate siteTemplate, TreeNode node)
        {
            CreateListFromTemplateDefinition(siteTemplate, node);
        }

        #endregion

        private TreeNode CreateNewNode(SharePointType sharePointType, string title, System.Windows.Forms.ContextMenuStrip contextMenuStrip, Template templateDefinition)
        {
            TreeNode node = new TreeNode(title, TreeImageUtils.GetAddIconIndex(sharePointType), TreeImageUtils.GetAddIconIndex(sharePointType));

            var dataNode = _projectData.Importer.GetNewDataNode(_projectData.ProjectParameter.ProjectVersion);
            dataNode.Title = title;

            dataNode.SharePointType = sharePointType;
            //dataNode.Deletable = true;
            dataNode.TemplateId = templateDefinition != null ? templateDefinition.ID : Guid.Empty;
            node.Tag = dataNode;
            node.ContextMenuStrip = contextMenuStrip;
            // node.ForeColor = Color.DarkOrange;
            return node;
        }

        private TreeNode CreateNewNode(SharePointType sharePointType, string title, System.Windows.Forms.ContextMenuStrip contextMenuStrip)
        {
            return CreateNewNode(sharePointType, title, contextMenuStrip, null);
        }

        // convert site to library
        void siteMenu1_Click(object sender, EventArgs e)
        {
            TreeNode node = targetTreeView.SelectedNode;

            DataNode data = node.Tag as DataNode;

            //_projectData.ActionItemHandler.ConvertNode(node, SharePointType.DocLibrary);
            data.SharePointType = SharePointType.DocLibrary;
            node.SelectedImageIndex = node.ImageIndex = TreeImageUtils.GetIconIndex(SharePointType.DocLibrary);

            node.SelectedImageIndex = TreeImageUtils.CalculateImageIndex(node, _projectData.ProjectParameter.ProjectVersion);
            node.SelectedImageIndex = TreeImageUtils.CalculateImageIndex(node, _projectData.ProjectParameter.ProjectVersion);

            node.ContextMenuStrip = _libraryMenu;

            foreach (TreeNode childNode in node.Nodes)
            {
                RecalculateNode(childNode, node, true);
            }
        }

        // add new library
        void siteMenu2_Click(object sender, EventArgs e)
        {
            TreeNode node = CreateNewNode(SharePointType.DocLibrary, "New Library", _libraryMenu);
            targetTreeView.SelectedNode.Nodes.Add(node);
            //_projectData.ActionItemHandler.InsertAction(node);
        }

        // delete selected site
        void siteMenu3_Click(object sender, EventArgs e)
        {
            //DeleteSelectedNode();
            RejectTreeNode(targetTreeView.SelectedNode);
        }

        void RejectTreeNode(TreeNode selectedNode)
        {

            var data = selectedNode.Tag as DataNode;

            //if (data.Version == _projectData.ProjectParameter.ProjectVersion && data.Version == data.PreviousVersion)
            if (!data.CommitedItem)
            {
                if (toolStripMenuItemDeletionConfirmDialog.Checked)
                {
                    if (MessageBox.Show("Are you sure you want to delete this items and subitems ?", "Delete item(s)", MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
                    {
                        return;
                    }
                }

                Cursor.Current = Cursors.WaitCursor;

                if (data != null && data.SharePointType != SharePointType.Application)
                {
                    //_projectData.ActionItemHandler.RemoveAction(selectedNode, selectedNode.Nodes.Count == 0);

                    RejectTreeNodesRecursive(selectedNode);
                    _treeNodeDebugger.PopulateTreeIntoList(sourceTreeView, targetTreeView);

                    foreach (TreeNode node in sourceTreeView.Nodes)
                    {
                        //SetNodeStatusColor(node);
                        ItemOperation.SetItemColorForChilds(node, false, _projectData.ProjectParameter.ProjectVersion);
                    }

                    selectedNode.TreeView.Nodes.Remove(selectedNode);
                    //_exportHandler.RemoveAction(selectedNode);
                }
                //_projectData.ActionItemHandler.SendHandlerInformation();
                Cursor.Current = Cursors.Default;
            }
            else
            {
                _infoMessageHandler.PrintInfo("A commited item cannot removed.");
            }
        }


        void spTreeView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                RejectTreeNode(((TreeView)sender).SelectedNode);
            }
            if (e.KeyCode == Keys.F5)
            {
                refreshTree(this, null);
            }
        }

        private void RejectTreeNodesRecursive(TreeNode treeNode)
        {
            var sourceNode = _treeNodeDebugger[treeNode];

            if (sourceNode != null)
            {
                DataNode data = sourceNode.Tag as DataNode;
                data.NodeDisabled = false;
            }

            foreach (TreeNode child in treeNode.Nodes)
            {
                //_projectData.ActionItemHandler.RemoveAction(child, false);
                RejectTreeNodesRecursive(child);
            }
        }

        #endregion

        #region Drag&Drop
        void spTreeView_DragDrop(object sender, DragEventArgs e)
        {
            TreeNode movedNode;

            if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
            {
                Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
                TreeNode destinationNode = ((TreeView)sender).GetNodeAt(pt);
                movedNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
                if (destinationNode != null)
                {
                    DataNode sourceData = movedNode.Tag as DataNode;
                    DataNode targetData = destinationNode.Tag as DataNode;

                    // drag & drop from source to target tree
                    if (destinationNode.TreeView != movedNode.TreeView)
                    {
                        //if (CheckDateIntegry(destinationNode, movedNode))
                        //{
                        if (_projectData.GovernanceData.IsMoveableToTarget(sourceData, targetData))
                        {
                            var node = (TreeNode)movedNode.Clone();

                            CleanupMigratedItemsRecursive(node);

                            //RecalculateNode(node, destinationNode);
                            RecalculateNode(node, destinationNode, false);
                            destinationNode.Nodes.Add(node);

                            destinationNode.Expand();

                            // Log to Recorder
                            //_projectData.ActionItemHandler.InsertFromSourceAction(movedNode, destinationNode);

                            //Remove Original Node
                            //movedNode.Remove();

                            try
                            {
                                Cursor.Current = Cursors.WaitCursor;
                                _treeNodeDebugger.PopulateTreeIntoList(sourceTreeView, targetTreeView);
                            }
                            finally
                            {
                                Cursor.Current = Cursors.Default;
                            }

                            SetNodeStatus(node, true);
                            ItemOperation.SetItemColorForChilds(movedNode, false, _projectData.ProjectParameter.ProjectVersion);
                        }
                        else
                        {
                            _infoMessageHandler.PrintInfo("It is not allowed to create a item below the pointed destination node");
                        }
                        //}
                    }
                    // drag & drop btw. target tree
                    else
                    {
                        if (movedNode.Parent != null && movedNode.Parent != destinationNode)
                        {
                            if (!IsSubNode(destinationNode, movedNode))
                            {
                                if (_projectData.GovernanceData.IsMoveableToTarget(sourceData, targetData))
                                {
                                    //if (CheckDateIntegry(destinationNode, movedNode))
                                    //{
                                    movedNode.Parent.Nodes.Remove(movedNode);
                                    //RecalculateNode(movedNode, destinationNode);
                                    RecalculateNode(movedNode, destinationNode, true);
                                    destinationNode.Nodes.Add(movedNode);

                                    // Log to Recorder
                                    //_projectData.ActionItemHandler.MoveAction(movedNode, destinationNode);

                                    destinationNode.Expand();
                                    //}
                                }
                                else
                                {
                                    _infoMessageHandler.PrintInfo("It is not allowed to create a item below the pointed destination node");
                                }
                            }
                            else
                            {
                                _infoMessageHandler.PrintInfo("Not allowed to move a parent item to it own child");
                            }
                        }
                    }
                }
            }
        }

        private void CleanupMigratedItemsRecursive(TreeNode node)
        {
            foreach (TreeNode child in node.Nodes)
            {
                var data = child.Tag as DataNode;

                if (data.NodeDisabled)
                {
                    node.Nodes.Remove(child);
                }
                else
                {
                    CleanupMigratedItemsRecursive(child);
                }
            }
        }

        private void SetNodeStatus(TreeNode targetNode, bool disable)
        {
            var sourceNode = _treeNodeDebugger[targetNode];

            if (sourceNode != null)
            {
                var data = sourceNode.Tag as DataNode;
                data.NodeDisabled = disable;

                //data.CommitedItem = false;

                //sourceNode.ForeColor = disable || data.Version != _currentProjectVersion ? Color.Gray : SystemColors.ControlText;

                foreach (TreeNode child in targetNode.Nodes)
                {
                    SetNodeStatus(child, disable);
                }
            }
        }

        bool HasNodeDocumentAsChild(TreeNode node)
        {
            foreach (TreeNode child in node.Nodes)
            {
                DataNode data = node.Tag as DataNode;

                if (data != null)
                {
                    if (data.SharePointType == SharePointType.Item
                        /*|| data.LiveLinkType == LiveLinkType.Document
                        || data.LiveLinkType == LiveLinkType.Item*/)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private bool HasNodeDocumentAsDescnendants(TreeNode node)
        {
            DataNode data = node.Tag as DataNode;

            if (data != null)
            {
                if (data.SharePointType == SharePointType.Item
                    /*|| data.LiveLinkType == LiveLinkType.Document
                    || data.LiveLinkType == LiveLinkType.Item*/)
                {
                    return true;
                }
            }

            foreach (TreeNode child in node.Nodes)
            {
                if (HasNodeDocumentAsDescnendants(child))
                {
                    return true;
                }
            }

            return false;

        }

        private bool CheckDataIntegry(TreeNode destinationNode, TreeNode movedNode)
        {
            //string format = "{0} Reason:{1}";
            string message = "Source and destination node not valid. Reason: technical issue.";
            bool ret = false;

            if (destinationNode.Tag != null && movedNode.Tag != null)
            {
                DataNode dataSource = movedNode.Tag as DataNode;
                DataNode dataTarget = destinationNode.Tag as DataNode;

                if (dataSource != null && dataTarget != null)
                {
                    // Document only under folder or libraries

                    if (/*dataSource.LiveLinkType == LiveLinkType.Item || dataSource.LiveLinkType == LiveLinkType.Document || */dataSource.SharePointType == SharePointType.Item)
                    {
                        if (dataTarget.SharePointType == SharePointType.DocLibrary || dataTarget.SharePointType == SharePointType.Folder)
                        {
                            ret = true;
                        }
                        message = "Item not moved. Reason: Items movable only inside a library or folder";
                        _infoMessageHandler.PrintInfo(message);
                        ret = false;
                    }

                    // workspaces/folders as site collection or site only witout direct assigned documents

                    if (dataTarget.SharePointType == SharePointType.Application || dataTarget.SharePointType == SharePointType.SiteCollection)
                    {
                        if (HasNodeDocumentAsChild(movedNode))
                        {
                            ret = false;
                            //message = "
                        }
                    }

                    if (/*dataSource.LiveLinkType == LiveLinkType.Item || dataSource.LiveLinkType == LiveLinkType.Document || */dataSource.SharePointType == SharePointType.Item)
                    {
                        if (dataTarget.SharePointType == SharePointType.DocLibrary || dataTarget.SharePointType == SharePointType.Folder)
                        {
                            return true;
                        }
                        return false;
                    }
                    return true;
                }
                else
                {
                    message = "Source and destination node tag not valid. Reason: tecnical issue.";
                    _infoMessageHandler.PrintInfo(message);
                    ret = false;
                }
            }

            //if (ret == false)
            //{
            //    txtInfoMessages.Text = message;
            //}

            return ret;
        }

        void treeView_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        void treeView_ItemDrag(object sender, ItemDragEventArgs e)
        {
            var node = e.Item as TreeNode;

            var data = node.Tag as DataNode;

            if (node != null && data != null && !data.NodeDisabled && _projectData.ProjectParameter.ProjectVersion == data.Version && !IsChildDisabled(node))
            {
                DoDragDrop(e.Item, DragDropEffects.Move);
            }
            else
            {
                _infoMessageHandler.PrintInfo("Move of item not allowed.");
            }
        }

        bool IsChildDisabled(TreeNode node)
        {
            var data = node.Tag as DataNode;

            if (data != null && data.NodeDisabled)
            {
                return true;
            }

            foreach (TreeNode child in node.Nodes)
            {
                if (IsChildDisabled(child))
                {
                    return true;
                }
            }
            return false;
        }

        private void spTreeView_ItemDrag(object sender, ItemDragEventArgs e)
        {
            var node = e.Item as TreeNode;

            if (node != null && node.Tag != null)
            {
                DataNode data = node.Tag as DataNode;

                if (_projectData.ProjectParameter.ProjectVersion == data.Version &&
                    data.CommitedItem == false &&
                    (_projectData.GovernanceData.IsNodeMovable(data) || SharePointStructureValidation.IsNodeMovable(data)))
                {
                    DoDragDrop(e.Item, DragDropEffects.Move);
                }
                else
                {
                    _infoMessageHandler.PrintInfo("Move of item not allowed.");
                }
            }
        }

        #endregion

        #region Nodes and Tree operations

        //private void SetNodeStatusColor(TreeNode node)
        //{
        //    DataNode dataNode = node.Tag as DataNode;

        //    if (dataNode == null || dataNode.NodeDisabled == true || dataNode.Version != _currentProjectVersion)
        //    {
        //        node.ForeColor = Color.Gray;
        //    }
        //    else
        //    {
        //        node.ForeColor = SystemColors.ControlText;
        //    }

        //    foreach (TreeNode child in node.Nodes)
        //    {
        //        SetNodeStatusColor(child);
        //    }
        //}

        //private void RecoloringTree(TreeNode node)
        //{
        //    DataNode dataNode = node.Tag as DataNode;

        //    if (dataNode.Version != _currentProjectVersion)
        //    {
        //        node.ForeColor = Color.Gray;
        //    }
        //    else
        //    {
        //        node.ForeColor = SystemColors.ControlText;
        //    }

        //    foreach (TreeNode child in node.Nodes)
        //    {
        //        RecoloringTree(child);
        //    }
        //}

        private void ReloadItemMenu(TreeNode node)
        {
            var currentDataNode = node.Tag as DataNode;
            if (node != null)
            {
                node.ContextMenuStrip = null;

                switch (currentDataNode.SharePointType)
                {
                    case SharePointType.Application:
                        node.ContextMenuStrip = _applicationMenu;
                        break;
                    case SharePointType.SiteCollection:
                        if (currentDataNode.TemplateId != Guid.Empty)
                        {
                            var template = TemplateDefinition.Instance.GetTemplate(currentDataNode.TemplateId) as SiteCollectionTemplate;

                            if (template != null)
                            {
                                node.ContextMenuStrip = CreateDynamicSiteCollectionMenu(template);
                            }
                            else
                            {
                                node.ContextMenuStrip = _siteCollectionMenu;
                            }
                        }
                        else
                        {
                            node.ContextMenuStrip = _siteCollectionMenu;
                        }
                        break;
                    case SharePointType.Site:
                        if (currentDataNode.TemplateId != Guid.Empty)
                        {
                            var template = TemplateDefinition.Instance.GetTemplate(currentDataNode.TemplateId) as SiteTemplate;

                            if (template != null)
                            {
                                node.ContextMenuStrip = CreateDynamicSiteMenu(template);
                            }
                            else
                            {
                                node.ContextMenuStrip = _siteMenu;
                            }
                        }
                        else
                        {
                            node.ContextMenuStrip = _siteMenu;
                        }
                        break;
                    case SharePointType.DocLibrary:
                        if (currentDataNode.TemplateId != Guid.Empty)
                        {
                            var template = TemplateDefinition.Instance.GetTemplate(currentDataNode.TemplateId) as LibraryTemplate;

                            if (template != null)
                            {
                                node.ContextMenuStrip = DynamicMenuOperations.CreateDynamicLibraryMenu(template, libMenu2_Click, libMenu3_Click);
                                DynamicMenuOperations.CreateSearchAndReplaceToolStripMenuItem(node.ContextMenuStrip, searchAndReplaceExportDialog_Click, !_projectData.ProjectParameter.ProjectIsCommited);
                            }
                            else
                            {
                                node.ContextMenuStrip = _libraryMenu;
                            }
                        }
                        else
                        {
                            node.ContextMenuStrip = _libraryMenu;
                        }
                        break;
                    case SharePointType.Folder:
                        node.ContextMenuStrip = _folderMenu;
                        break;
                }
            }

            #region Recusive iteration
            foreach (TreeNode childNode in node.Nodes)
            {
                ReloadItemMenu(childNode);
            }
            #endregion
        }

        private void RecalculateNode(TreeNode movedNode, TreeNode desitnationNode, bool targetTreeViewMove)
        {

            #region recalculation
            var parentDataNode = desitnationNode.Tag as DataNode;
            var currentDataNode = movedNode.Tag as DataNode;

            if (currentDataNode != null && parentDataNode != null)
            {
                movedNode.ContextMenuStrip = null;

                switch (parentDataNode.SharePointType)
                {
                    case SharePointType.Application:
                        currentDataNode.SharePointType = SharePointType.SiteCollection;
                        movedNode.ContextMenuStrip = _siteCollectionMenu;
                        break;
                    case SharePointType.SiteCollection:
                    case SharePointType.Site:

                        if (!targetTreeViewMove)
                        {
                            currentDataNode.SharePointType = _projectData.Importer.GetSharePointType(currentDataNode);
                        }

                        if (currentDataNode.SharePointType == SharePointType.SiteCollection)
                        {
                            currentDataNode.SharePointType = SharePointType.Site;
                        }

                        if (currentDataNode.SharePointType == SharePointType.Folder)
                        {
                            currentDataNode.SharePointType = SharePointType.DocLibrary;
                        }

                        if (currentDataNode.SharePointType == SharePointType.Site)
                        {
                            movedNode.ContextMenuStrip = _siteMenu;
                        }

                        if (currentDataNode.SharePointType == SharePointType.DocLibrary)
                        {
                            movedNode.ContextMenuStrip = _libraryMenu;
                        }

                        if (currentDataNode.SharePointType == SharePointType.Folder)
                        {
                            movedNode.ContextMenuStrip = _folderMenu;
                        }

                        //if (currentDataNode.LiveLinkType == LiveLinkType.NotALiveLinkSource)
                        //{
                        //    if (currentDataNode.SharePointType == SharePointType.Site)
                        //    {
                        //        movedNode.ContextMenuStrip = _siteMenu;
                        //        currentDataNode.SharePointType = SharePointType.Site;
                        //    }
                        //    else
                        //    {
                        //        movedNode.ContextMenuStrip = _libraryMenu;
                        //        currentDataNode.SharePointType = SharePointType.DocLibrary;
                        //    }
                        //}
                        break;
                    case SharePointType.DocLibrary:
                    case SharePointType.Folder:

                        if (!targetTreeViewMove)
                        {
                            currentDataNode.SharePointType = _projectData.Importer.GetSharePointType(currentDataNode);
                        }
                        if (currentDataNode.SharePointType == SharePointType.SiteCollection
                            || currentDataNode.SharePointType == SharePointType.Site
                            || currentDataNode.SharePointType == SharePointType.DocLibrary
                            || currentDataNode.SharePointType == SharePointType.Folder)
                        {
                            currentDataNode.SharePointType = SharePointType.Folder;
                            movedNode.ContextMenuStrip = _folderMenu;
                        }

                        //if (currentDataNode.LiveLinkType == LiveLinkType.Item)
                        //{
                        //    currentDataNode.SharePointType = SharePointType.Item;
                        //}
                        //else if (currentDataNode.LiveLinkType == LiveLinkType.Document)
                        //{
                        //    currentDataNode.SharePointType = SharePointType.Document;
                        //}
                        //else if (currentDataNode.LiveLinkType == LiveLinkType.NotALiveLinkSource)
                        //{
                        //    //if (currentDataNode.SharePointType == SharePointType.Folder)
                        //    //{
                        //    movedNode.ContextMenuStrip = _folderMenu;
                        //    currentDataNode.SharePointType = SharePointType.Folder;
                        //    //}
                        //    //else
                        //    //{
                        //    //    //Console.WriteLine("Check situation");
                        //    //    movedNode.ContextMenuStrip = _libraryMenu;
                        //    //    currentDataNode.SharePointType = SharePointType.DocLibrary;
                        //    //}

                        //}
                        //else
                        //{
                        //    currentDataNode.SharePointType = SharePointType.Folder;
                        //    movedNode.ContextMenuStrip = _folderMenu;
                        //}
                        break;
                }

                movedNode.ImageIndex = movedNode.SelectedImageIndex = TreeImageUtils.GetIconIndex(currentDataNode.SharePointType);
                movedNode.SelectedImageIndex = TreeImageUtils.CalculateImageIndex(movedNode, _projectData.ProjectParameter.ProjectVersion);
                movedNode.ImageIndex = TreeImageUtils.CalculateImageIndex(movedNode, _projectData.ProjectParameter.ProjectVersion);
            }
            #endregion

            #region Recusive iteration
            foreach (TreeNode childNode in movedNode.Nodes)
            {
                RecalculateNode(childNode, movedNode, targetTreeViewMove);
            }
            #endregion

        }

        private bool IsSubNode(TreeNode destinationNode, TreeNode movedNode)
        {
            if (destinationNode == movedNode)
            {
                return true;
            }
            else
            {
                foreach (TreeNode child in movedNode.Nodes)
                {
                    if (IsSubNode(child, destinationNode))
                    {
                        return true;
                    }
                }
                return false;
            }
        }

        #endregion

        #region MenuOperations

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void UpdateMenuItems()
        {

            #region Update Application Title

            var projectTitle = string.IsNullOrEmpty(_projectData.ProjectParameter.ProjectName) ? "undefined" : _projectData.ProjectParameter.ProjectName;

            this.Text = string.Format("{0} - {1} -- Migration Studio", projectTitle, ConfigurationManager.AppSettings["ProjectTitle"]);

            
            #endregion

            #region commitMappingToolStripMenuItem
            if (_projectData.ProjectParameter.SelectedSharePointItemId > 0 && _projectData.ProjectParameter.ProjectIsCommited != true)
            {
                commitMappingToolStripMenuItem.Enabled = true;
                tspImportDeploymentReport.Enabled = true;
            }
            else
            {
                commitMappingToolStripMenuItem.Enabled = false;
                tspImportDeploymentReport.Enabled = false;
            }
            #endregion

            #region loadDeltaMigrationFromMenuItemDashboardToolStrip / toolStripMenuItemLoadDeltaMigration
            loadDeltaMigrationFromMenuItemDashboardToolStrip.Enabled = _projectData.ProjectParameter.ProjectIsCommited && _projectData.ProjectParameter.SelectedSharePointItemId > 0;
            toolStripMenuItemLoadDeltaMigration.Enabled = _projectData.ProjectParameter.ProjectIsCommited;
            #endregion
            
        }

        #region Open/Save to Filesystem


        private void importToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //throw new NotImplementedException();

            //OpenFileDialog dlg = new OpenFileDialog();
            //dlg.RestoreDirectory = true;
            //dlg.Filter = "Tzunami Exporter File|*.tdx";
            //dlg.Title = "Select a Tzunami Exporter File";

            if (_projectData.Importer.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //Cursor.Current = Cursors.WaitCursor;
                _progressScreen = new ProgressScreen();
                _progressScreen.CenterForm(this).Show();
                try
                {
                    //_separateDataFiles.Clear();
                    //_dataFilesFolder = Path.GetDirectoryName(dlg.FileName);
                    //mainTree.Nodes.Clear();
                    targetTreeView.Nodes.Clear();

                    //var fileName = string.Format(@"{0}\{1}", _dataFilesFolder, dlg.SafeFileName);
                    _projectData.ProjectParameter.ResetProject();
                    //_projectData.Importer.ProgressInit += ProgressInit;
                    //_projectData.Importer.ProgressUpdate += ProgressUpdate;
                    _projectData.Importer.Import(sourceTreeView, _projectData.ProjectParameter.ProjectVersion, loadItemsToolStripMenuItem.Checked);


                    //var rootNode = new TreeNode("LiveLink tree", 2, 2);
                    //DataNode dataNodeLL = new DataNode() { Title = "LiveLink tree", LiveLinkType = 0 };
                    //rootNode.Tag = dataNodeLL;
                    //mainTree.Nodes.Add(rootNode);

                    //var spRootNode = new TreeNode("SharePoint");
                    //DataNode dataNodeSP = new DataNode() { Title = "LiveLink tree", /*SourceParentNode = null,*/ LiveLinkType = LiveLinkType.NotDefined, SharePointType = SharePointType.Application };
                    //spRootNode.Tag = dataNodeSP;
                    //spRootNode.ContextMenuStrip = _applicationMenu;
                    //spTreeView.Nodes.Add(spRootNode);
                    CreateSPTreeViewRoot(_projectData.ProjectParameter.ProjectVersion);

                    //var doc = new XmlDocument();
                    //doc.Load(string.Format(@"{0}\{1}", _dataFilesFolder, dlg.SafeFileName));

                    //var folders = doc.DocumentElement.SelectSingleNode("folders");

                    //BuildNode(folders, rootNode);

                    //_projectData.ActionItemHandler.ResetActions();
                    //exportHandlerInformationUpdate(_projectData.ActionItemHandler.ActionList.Count);

                    FillDataView(null, true);
                }
                finally
                {
                    //_projectData.Importer.ProgressInit -= ProgressInit;
                    //_projectData.Importer.ProgressUpdate -= ProgressUpdate;
                    if (_progressScreen != null && !_progressScreen.IsDisposed)
                    {
                        _progressScreen.Close();
                    }
                    UpdateMenuItems();
                }
            }

        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_projectData.ProjectParameter.SelectedSharePointItemId == -1)
            {
                _infoMessageHandler.PrintError("Save action denied, no project was loaded in mapper");
            }
            else
            {
                if (string.IsNullOrEmpty(_projectFileName))
                {
                    saveAsToolStripMenuItem_Click(sender, e);
                }
                else
                {
                    _progressScreen = new ProgressScreen();
                    _progressScreen.CenterForm(this).Show();

                    try
                    {
                        FileSystemProjectPersistence projectPersistence = new FileSystemProjectPersistence();
                        projectPersistence.ProgressInit += ProgressInit;
                        projectPersistence.ProgressUpdate += ProgressUpdate;
                        projectPersistence.ProgressUpdateDone += ProgressUpdateDone;

                        //_projectData = new ProjectData() { Importer = _sourceImporter, ActionItemHandler = _exportHandler, GovernanceData = _governanceData, ProjectParameter = new ProjectParameter()};
                        //_projectData.ProjectParameter.SelectedSharePointItemId = _selectedSharePointItemId;
                        //_projectData.ProjectParameter.ProjectVersion = _currentProjectVersion;
                        projectPersistence.Save(_projectFileName, sourceTreeView, targetTreeView, _projectData);

                        _infoMessageHandler.PrintInfo("Project successfull saved");
                    }
                    catch (Exception ex)
                    {
                        _infoMessageHandler.PrintError("Error during save action:" + ex.Message);
                        MessageBox.Show("Project save failed. Please try it again or contact your Migration support.", "Error");
                    }
                    finally
                    {
                        _progressScreen.Close();
                    }
                }
            }
            UpdateMenuItems();
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_projectData.ProjectParameter.SelectedSharePointItemId == -1)
            {
                _infoMessageHandler.PrintError("Save action denied, no project was loaded in mapper");
            }
            else
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.RestoreDirectory = true;
                dlg.Filter = "Mapper File|*.amf";
                dlg.Title = "Select a Mapper File ";

                if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    //Cursor.Current = Cursors.WaitCursor;

                    _projectFileName = dlg.FileName;

                    _progressScreen = new ProgressScreen();
                    _progressScreen.CenterForm(this).Show();

                    try
                    {
                        FileSystemProjectPersistence projectPersistence = new FileSystemProjectPersistence();
                        projectPersistence.ProgressInit += ProgressInit;
                        projectPersistence.ProgressUpdate += ProgressUpdate;
                        projectPersistence.ProgressUpdateDone += ProgressUpdateDone;

                        //ProjectData data = new ProjectData() { Importer = _sourceImporter, ActionItemHandler = _exportHandler, GovernanceData = _governanceData, SelectedSharePointItemId = _selectedSharePointItemId };
                        //_projectData = new ProjectData() { Importer = _sourceImporter, ActionItemHandler = _exportHandler, GovernanceData = _governanceData, ProjectParameter = new ProjectParameter() };
                        //_projectData.ProjectParameter.SelectedSharePointItemId = _selectedSharePointItemId;
                        //_projectData.ProjectParameter.ProjectVersion = _currentProjectVersion;

                        projectPersistence.Save(_projectFileName, sourceTreeView, targetTreeView, _projectData);
                        _infoMessageHandler.PrintInfo("Project successfull saved");
                    }
                    catch (Exception ex)
                    {
                        _infoMessageHandler.PrintError("Error during save action:" + ex.Message);
                        MessageBox.Show("Project save failed. Please try it again or contact your Migration support.", "Error");
                    }
                    finally
                    {
                        _progressScreen.Close();
                    }
                }
            }
            UpdateMenuItems();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {

            OpenFileDialog dlg = new OpenFileDialog();
            dlg.RestoreDirectory = true;
            dlg.Filter = "Mapper File|*.amf";
            dlg.Title = "Select a Mapper File ";

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //Cursor.Current = Cursors.WaitCursor;
                _progressScreen = new ProgressScreen();
                _progressScreen.CenterForm(this).Show();

                try
                {
                    _projectFileName = dlg.FileName;

                    sourceTreeView.ImageList = _projectData.Importer.GetImageListList();

                    FileSystemProjectPersistence projectPersistence = new FileSystemProjectPersistence();
                    projectPersistence.ProgressInit += ProgressInit;
                    projectPersistence.ProgressUpdate += ProgressUpdate;
                    projectPersistence.ProgressUpdateDone += ProgressUpdateDone;

                    //_projectData = new ProjectData() { Importer = _sourceImporter, ActionItemHandler = _exportHandler };

                    //toolStripLoadLabel.Text = "Load data files";
                    //toolStripLoadLabel.Visible = true;
                    //toolStripLoadProgress.Visible = true;
                    //Refresh();

                    _projectData.ProjectParameter.ResetProject();
                    projectPersistence.Load(_projectFileName, sourceTreeView, targetTreeView, _projectData);
                    //_selectedSharePointItemId = _projectData.ProjectParameter.SelectedSharePointItemId;
                    //_currentProjectVersion = _projectData.ProjectParameter.ProjectVersion;
                    //_projectData.ProjectParameter.ProjectVersion = _projectData.GovernanceData;

                    CreateApplicationDynamicMenu();

                    foreach (TreeNode node in targetTreeView.Nodes)
                    {
                        ReloadItemMenu(node);
                        //RecoloringTree(node);
                        ItemOperation.SetItemColorForChilds(node, true, _projectData.ProjectParameter.ProjectVersion);
                        node.ContextMenuStrip = _applicationMenu;
                    }

                    _treeNodeDebugger.PopulateTreeIntoList(sourceTreeView, targetTreeView);

                    foreach (TreeNode node in sourceTreeView.Nodes)
                    {
                        ItemOperation.SetItemColorForChilds(node, false, _projectData.ProjectParameter.ProjectVersion);
                        //SetNodeStatusColor(node);
                    }
                }
                catch (Exception ex)
                {
                    _infoMessageHandler.PrintError("Error during open project file:" + ex.InnerException.Message);
                }
                finally
                {
                    _progressScreen.Close();
                }
                FillDataView(null, true);
                //exportHandlerInformationUpdate(_projectData.ActionItemHandler.ActionList.Count);
            }
            UpdateMenuItems();
        }

        #endregion

        #region ProgressBar
        void ProgressUpdateDone(object sender)
        {
        }

        void ProgressUpdate(object sender, long currentStep)
        {
            _progressScreen.ProgressValue = (int)currentStep;
        }

        void ProgressInit(object sender, long stepCount, string name)
        {
            _progressScreen.ProgressMaximum = (int)stepCount;
            _progressScreen.Message = name;
        }
        #endregion

        #region Export Action List
        //private void exportToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    SaveFileDialog dlg = new SaveFileDialog();
        //    dlg.RestoreDirectory = true;
        //    dlg.Filter = "Csv File|*.csv";
        //    dlg.Title = "Select a Csv File ";
        //    dlg.FileName = "ActionList";

        //    if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //    {
        //        Cursor.Current = Cursors.WaitCursor;

        //        try
        //        {
        //            _projectData.ActionItemHandler.SaveAsCsv(dlg.FileName);
        //        }
        //        finally
        //        {
        //            Cursor.Current = Cursors.Default;
        //        }
        //    }
        //    UpdateMenuItems();
        //}
        #endregion

        #region Import / Publish / Open from Dashboard
        private void importFromDashboardToolStripMenuItem_Click_legacy(object sender, EventArgs e)
        {
            try
            {
                //var data = SharePoint2010ApplicationConfiguration.LoadGovernanceData();
                _projectData.GovernanceData = SharePoint2010ApplicationConfiguration.LoadGovernanceData();
            }
            catch (Exception ex)
            {
                _infoMessageHandler.PrintError(ex.Message);
            }
        }

        private void importFromDashboardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                ImportFromPortal dlg = new ImportFromPortal(true);
                var result = dlg.OpenDialog();

                if (result.DialogResult == System.Windows.Forms.DialogResult.OK)
                {

                    //this.Text = string.Format("LiveLink to SharePoint Mapper : {0}", result.ProjectName);

                    _progressScreen = new ProgressScreen();
                    _progressScreen.CenterForm(this).Show();

                    targetTreeView.Nodes.Clear();
                    sourceTreeView.Nodes.Clear();


                    SharePoint2010Persistence instance = new SharePoint2010Persistence();
                    instance.ProgressInit += ProgressInit;
                    instance.ProgressUpdate += ProgressUpdate;

                    _projectData.ProjectParameter.ResetProject();
                    _projectData.ProjectParameter.SelectedSharePointItemId = result.SelectedSharePointItemId;

                    _projectData.ProjectParameter.ProjectName = instance.GetItemTitle(result.SelectedSharePointItemId);

                    var folder = instance.LoadZipFileAndExtractToUserFolder(ConfigurationManager.AppSettings["ImportStructureFile"], result.SelectedSharePointItemId);

                    if (folder == null)
                    {
                        _infoMessageHandler.PrintError("Record file not found, please contact HelpDesk");
                    }
                    else
                    {

                        _projectData.Importer.SetConfiguration(string.Format(@"{0}\{1}", folder, ConfigurationManager.AppSettings["MainImportTDXName"]));

                        try
                        {
                            targetTreeView.BeginUpdate();
                            sourceTreeView.BeginUpdate();

                            _projectData.Importer.Import(sourceTreeView, _projectData.ProjectParameter.ProjectVersion, loadItemsToolStripMenuItem.Checked);

                            CreateSPTreeViewRoot(_projectData.ProjectParameter.ProjectVersion);

                            //_projectData.ActionItemHandler.ResetActions();
                            //exportHandlerInformationUpdate(_projectData.ActionItemHandler.ActionList.Count);

                            FillDataView(null, true);
                            targetTreeView.EndUpdate();
                            sourceTreeView.EndUpdate();

                            _treeNodeDebugger.PopulateTreeIntoList(sourceTreeView, targetTreeView);

                            _infoMessageHandler.PrintInfo("Structure definition successfull loaded.");
                        }
                        catch (Exception ex)
                        {
                            _infoMessageHandler.PrintError("Failure during structure definition import [" + ex.Message + "]");
                        }
                        finally
                        {
                            Directory.Delete(folder, true);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                _infoMessageHandler.PrintError("Error open Inport Dialog:" + ex.Message);
            }
            finally
            {
                if (_progressScreen != null && !_progressScreen.IsDisposed)
                {
                    _progressScreen.Close();
                }
                UpdateMenuItems();
            }

        }

        private void publishToDashboardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                _progressScreen = new ProgressScreen();
                _progressScreen.CenterForm(this).Show();

                if (_projectData.ProjectParameter.SelectedSharePointItemId > -1)
                {
                    SharePoint2010ProjectPersistence projectPersistence = new SharePoint2010ProjectPersistence();
                    projectPersistence.ProgressInit += ProgressInit;
                    projectPersistence.ProgressUpdate += ProgressUpdate;

                    projectPersistence.Save(_projectData.ProjectParameter.SelectedSharePointItemId, sourceTreeView, targetTreeView, _projectData);
                    _infoMessageHandler.PrintInfo("Project successfull saved");
                }
                else
                {
                    _infoMessageHandler.PrintError("Save action denied, no project loaded");
                }
            }
            catch (Exception ex)
            {
                _infoMessageHandler.PrintError("Error during publising of project from portal:" + ex.Message);
                MessageBox.Show("Project save failed. Please try again or save it on your PC and contact your Migration support.", "Error");
            }
            finally
            {
                _progressScreen.Close();
                UpdateMenuItems();
            }
        }

        private void openFromDashboardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ImportFromPortal dlg = new ImportFromPortal(false);
            var result = dlg.OpenDialog();

            if (result.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                _progressScreen = new ProgressScreen();
                _progressScreen.CenterForm(this).Show();

                try
                {
                    sourceTreeView.ImageList = _projectData.Importer.GetImageListList();

                    SharePoint2010ProjectPersistence projectPersistence = new SharePoint2010ProjectPersistence();
                    projectPersistence.ProgressInit += ProgressInit;
                    projectPersistence.ProgressUpdate += ProgressUpdate;

                    _projectData.ProjectParameter.ResetProject();
                    _projectData.ProjectParameter.SelectedSharePointItemId = result.SelectedSharePointItemId;

                    SharePoint2010Persistence instance = new SharePoint2010Persistence();

                    //ProjectData data = new ProjectData() { Importer = _sourceImporter, ActionItemHandler = _exportHandler, SelectedSharePointItemId = _selectedSharePointItemId };
                    //_projectData = new ProjectData() { Importer = _sourceImporter, ActionItemHandler = _exportHandler };

                    projectPersistence.Load(_projectData.ProjectParameter.SelectedSharePointItemId, sourceTreeView, targetTreeView, _projectData);

                    _projectData.ProjectParameter.ProjectName = instance.GetItemTitle(result.SelectedSharePointItemId);

                    CreateApplicationDynamicMenu();

                    foreach (TreeNode node in targetTreeView.Nodes)
                    {
                        ReloadItemMenu(node);
                        ItemOperation.SetItemColorForChilds(node, true, _projectData.ProjectParameter.ProjectVersion);
                        //RecoloringTree(node);
                        node.ContextMenuStrip = _applicationMenu;
                    }

                    foreach (TreeNode node in sourceTreeView.Nodes)
                    {
                        //SetNodeStatusColor(node);
                        ItemOperation.SetItemColorForChilds(node, false, _projectData.ProjectParameter.ProjectVersion);
                    }

                    FillDataView(null, true);
                    //exportHandlerInformationUpdate(_projectData.ActionItemHandler.ActionList.Count);

                    _treeNodeDebugger.PopulateTreeIntoList(sourceTreeView, targetTreeView);

                    _infoMessageHandler.PrintInfo("Project from dasboard loaded");
                }
                catch (Exception ex)
                {
                    _infoMessageHandler.PrintError("Error during open of project from portal:" + ex.Message);
                }
                finally
                {
                    _progressScreen.Close();
                    UpdateMenuItems();
                }
            }
        }

        #endregion

        #region DeltaMapping
        private void loadDeltaMigrationFromDashboard(object sender, EventArgs e)
        {
            try
            {
                _progressScreen = new ProgressScreen();
                _progressScreen.CenterForm(this).Show();

                SharePoint2010Persistence instance = new SharePoint2010Persistence();
                instance.ProgressInit += ProgressInit;
                instance.ProgressUpdate += ProgressUpdate;

                //var itemExists = instance.FileExistsInFolder(_projectData.ProjectParameter.SelectedSharePointItemId, ConfigurationManager.AppSettings["ImportDeltaStructureFile"]);

                var path = instance.LoadZipFileAndExtractToUserFolder(ConfigurationManager.AppSettings["ImportDeltaStructureFile"], _projectData.ProjectParameter.SelectedSharePointItemId);

                if (path == null)
                {
                    MessageBox.Show(string.Format("No Delta migration export ({0}) in Dashboard available", ConfigurationManager.AppSettings["ImportDeltaStructureFile"]), "Alert");
                }
                else
                {

                    try
                    {
                        targetTreeView.BeginUpdate();
                        sourceTreeView.BeginUpdate();
                        _projectData.Importer.SetConfiguration(string.Format(@"{0}\{1}", path, ConfigurationManager.AppSettings["DeltaImportTDXName"]));
                        var result = _projectData.Importer.DeltaUpdate(sourceTreeView, targetTreeView, _projectData.ProjectParameter.ProjectVersion);

                        if (MessageBox.Show(string.Format("{0} source object added or updated. Do you want to save the delta update report ? ", result.Count), "Update done", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                        {
                            SaveFileDialog saveDlg = new SaveFileDialog();
                            saveDlg.RestoreDirectory = true;
                            saveDlg.Filter = "Excel File|*.xlsx";
                            saveDlg.Title = "Save Update report";

                            if (saveDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                _projectData.Importer.SaveUpdateResult(result, saveDlg.FileName);
                            }
                        }
                        foreach (TreeNode node in targetTreeView.Nodes)
                        {
                            ReloadItemMenu(node);
                            //RecoloringTree(node);
                            ItemOperation.SetItemColorForChilds(node, true, _projectData.ProjectParameter.ProjectVersion);
                            node.ContextMenuStrip = _applicationMenu;
                            TreeImageUtils.SetIconIndex(node, _projectData.ProjectParameter.ProjectVersion);
                        }

                        _treeNodeDebugger.PopulateTreeIntoList(sourceTreeView, targetTreeView);

                        foreach (TreeNode node in sourceTreeView.Nodes)
                        {
                            ItemOperation.SetItemColorForChilds(node, false, _projectData.ProjectParameter.ProjectVersion);
                            //SetNodeStatusColor(node);
                        }

                        FillDataView(null, true);
                        _projectData.ProjectParameter.ProjectIsCommited = false;
                        targetTreeView.EndUpdate();
                        sourceTreeView.EndUpdate();
                    }
                    finally
                    {
                        Directory.Delete(path, true);
                    }

                }
            }
            finally
            {
                if (_progressScreen != null && !_progressScreen.IsDisposed)
                {
                    _progressScreen.Close();
                }
                UpdateMenuItems();
            }
        }

        private void loadDeltaMigrationFromFile(object sender, EventArgs e)
        {

            if (_projectData.Importer.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //Cursor.Current = Cursors.WaitCursor;
                _progressScreen = new ProgressScreen();
                _progressScreen.CenterForm(this).Show();

                try
                {
                    targetTreeView.BeginUpdate();
                    sourceTreeView.BeginUpdate();

                    var result = _projectData.Importer.DeltaUpdate(sourceTreeView, targetTreeView, _projectData.ProjectParameter.ProjectVersion);

                    if (MessageBox.Show(string.Format("{0} source object(s) added or updated. Do you want to save the delta update report ? ", result.Count), "Update done", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        SaveFileDialog saveDlg = new SaveFileDialog();
                        saveDlg.RestoreDirectory = true;
                        saveDlg.Filter = "Excel File|*.xlsx";
                        saveDlg.Title = "Save Update report";

                        if (saveDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            _projectData.Importer.SaveUpdateResult(result, saveDlg.FileName);
                        }
                    }

                    foreach (TreeNode node in targetTreeView.Nodes)
                    {
                        ReloadItemMenu(node);
                        //RecoloringTree(node);
                        ItemOperation.SetItemColorForChilds(node, true, _projectData.ProjectParameter.ProjectVersion);
                        node.ContextMenuStrip = _applicationMenu;
                        TreeImageUtils.SetIconIndex(node, _projectData.ProjectParameter.ProjectVersion);
                    }

                    _treeNodeDebugger.PopulateTreeIntoList(sourceTreeView, targetTreeView);

                    foreach (TreeNode node in sourceTreeView.Nodes)
                    {
                        ItemOperation.SetItemColorForChilds(node, false, _projectData.ProjectParameter.ProjectVersion);
                        //SetNodeStatusColor(node);
                    }

                    FillDataView(null, true);
                    _projectData.ProjectParameter.ProjectIsCommited = false;
                    targetTreeView.EndUpdate();
                    sourceTreeView.EndUpdate();
                }
                finally
                {
                    if (_progressScreen != null && !_progressScreen.IsDisposed)
                    {
                        _progressScreen.Dispose();
                    }

                    UpdateMenuItems();
                }
            }
        }

        private void commitMappingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("A commit closes the current mapping and no changes can be done. A commit cannot undo. Save project after commit to dashboard or file system", "Commit mapping", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                sourceTreeView.BeginUpdate();
                targetTreeView.BeginUpdate();
                Cursor.Current = Cursors.WaitCursor;
                try
                {
                    _projectData.ProjectParameter.ProjectVersion++;
                    Console.WriteLine(string.Format("1.Start commit, set SetItemColorForChilds for SharePoint tree[{0}]", DateTime.Now));
                    foreach (TreeNode node in targetTreeView.Nodes)
                    {
                        ReloadItemMenu(node);
                        ItemOperation.SetItemColorForChilds(node, true, _projectData.ProjectParameter.ProjectVersion);
                        //node.ContextMenuStrip = _applicationMenu;
                    }

                    Console.WriteLine(string.Format("2.PopulateTreeIntoList[{0}]", DateTime.Now));
                    _treeNodeDebugger.PopulateTreeIntoList(sourceTreeView, targetTreeView);

                    Console.WriteLine(string.Format("3.Set SetItemColorForChilds for livelink tree[{0}]", DateTime.Now));
                    foreach (TreeNode node in sourceTreeView.Nodes)
                    {
                        ItemOperation.SetItemColorForChilds(node, false, _projectData.ProjectParameter.ProjectVersion);
                    }

                    FillDataView(null, true);
                    _projectData.ProjectParameter.ProjectIsCommited = true;
                    Console.WriteLine(string.Format("4.CommitTreeNodesRecursive[{0}]", DateTime.Now));
                    CommitTreeNodesRecursive();
                    Console.WriteLine(string.Format("5.SetIconIndex[{0}]", DateTime.Now));
                    TreeImageUtils.SetIconIndex(targetTreeView, _projectData.ProjectParameter.ProjectVersion);
                    Console.WriteLine(string.Format("6.Commit done[{0}]", DateTime.Now));
                }
                finally
                {
                    sourceTreeView.EndUpdate();
                    targetTreeView.EndUpdate();
                    Cursor.Current = Cursors.Default;
                    UpdateMenuItems();
                }

            }
        }

        private void tspUnCommitProject_Click(object sender, EventArgs e)
        {
            sourceTreeView.BeginUpdate();
            targetTreeView.BeginUpdate();
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                FillDataView(null, true);
                _projectData.ProjectParameter.ProjectVersion = 0;
                _projectData.ProjectParameter.ProjectIsCommited = false;
                Console.WriteLine(string.Format("1.UnCommitTreeNodesRecursive[{0}]", DateTime.Now));
                UnCommitTreeNodesRecursive();
                Console.WriteLine(string.Format("2.SetItemColorForChilds in source[{0}]", DateTime.Now));
                foreach (TreeNode node in sourceTreeView.Nodes)
                {
                    ItemOperation.SetItemColorForChilds(node, false, _projectData.ProjectParameter.ProjectVersion);
                }
                Console.WriteLine(string.Format("3.SetItemColorForChilds in target[{0}]", DateTime.Now));
                foreach (TreeNode node in targetTreeView.Nodes)
                {
                    ItemOperation.SetItemColorForChilds(node, true, _projectData.ProjectParameter.ProjectVersion);
                }
                //Console.WriteLine(string.Format("2.SetIconIndex[{0}]", DateTime.Now));
                //TreeImageUtils.SetIconIndex(targetTreeView, _projectData.ProjectParameter.ProjectVersion);
                Console.WriteLine(string.Format("4.UnCommit done[{0}]", DateTime.Now));
            }
            finally
            {
                sourceTreeView.EndUpdate();
                targetTreeView.EndUpdate();
                Cursor.Current = Cursors.Default;
                UpdateMenuItems();
            }
        }

        private void UnCommitTreeNodesRecursive()
        {
            var res = MessageBox.Show("An uncommit sets the versioning to zero. A Delta Export of the current mapping is not longer available. Please proceed only if the migration is final done and updates in mapping are needed!", "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Error);

            if (res == System.Windows.Forms.DialogResult.Yes)
            {

                foreach (TreeNode child in targetTreeView.Nodes)
                {
                    UnCommitTreeNodesRecursive(child);
                }

                foreach (TreeNode child in sourceTreeView.Nodes)
                {
                    UnCommitTreeNodesRecursive(child);
                }
            }

        }

        private void UnCommitTreeNodesRecursive(TreeNode treeNode)
        {
            DataNode data = treeNode.Tag as DataNode;
            data.CommitedItem = false;
            data.PreviousVersion = 0;
            data.Version = 0;

            foreach (TreeNode child in treeNode.Nodes)
            {
                UnCommitTreeNodesRecursive(child);
            }
        }

        private void CommitTreeNodesRecursive()
        {
            foreach (TreeNode child in targetTreeView.Nodes)
            {
                CommitTreeNodesRecursive(child);
            }

            foreach (TreeNode child in sourceTreeView.Nodes)
            {
                CommitTreeNodesRecursive(child);
            }
        }

        private void CommitTreeNodesRecursive(TreeNode treeNode)
        {

            DataNode data = treeNode.Tag as DataNode;
            data.CommitedItem = true;

            foreach (TreeNode child in treeNode.Nodes)
            {
                CommitTreeNodesRecursive(child);
            }
        }
        #endregion

        #endregion

        #region DataValidation
        private void runDataValidationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (TreeNode node in targetTreeView.Nodes)
            {
                //RecoloringTree(node);
                SharePointStructureValidation.ResetValidation(node);
                SharePointStructureValidation.ValidateTreeNode(node);
                ItemOperation.SetItemColorForChilds(node, true, _projectData.ProjectParameter.ProjectVersion);
            }
            UpdateMenuItems();
        }

        // SharePoint validation check
        //private bool ValidateTree(TreeNode node)
        //{
        //    bool valid = true;

        //    if (node.Parent != null)
        //    {

        //        DataNode dataNode = node.Tag as DataNode;
        //        DataNode parentDataNode = node.Parent.Tag as DataNode;

        //        #region Validation

        //        switch (dataNode.SharePointType)
        //        {
        //            case SharePointType.Document:
        //            case SharePointType.Item:
        //                if (parentDataNode.SharePointType != SharePointType.Folder
        //                    && parentDataNode.SharePointType != SharePointType.DocLibrary)
        //                {
        //                    valid = false;
        //                }
        //                break;
        //            case SharePointType.Folder:
        //                if (parentDataNode.SharePointType != SharePointType.DocLibrary
        //                    && parentDataNode.SharePointType != SharePointType.Folder)
        //                {
        //                    valid = false;
        //                }
        //                break;
        //            case SharePointType.DocLibrary:
        //                if (parentDataNode.SharePointType != SharePointType.Site
        //                    && parentDataNode.SharePointType != SharePointType.SiteCollection)
        //                {
        //                    valid = false;
        //                }
        //                break;
        //            case SharePointType.Site:
        //                if (parentDataNode.SharePointType != SharePointType.SiteCollection
        //                    && parentDataNode.SharePointType != SharePointType.Site)
        //                {
        //                    valid = false;
        //                }
        //                break;
        //            case SharePointType.SiteCollection:
        //                if (parentDataNode.SharePointType != SharePointType.Application)
        //                {
        //                    valid = false;
        //                }
        //                break;
        //        }

        //        #endregion
        //    }
        //    #region Recursive tree iteration

        //    foreach (TreeNode child in node.Nodes)
        //    {
        //        if (!ValidateTree(child))
        //        {
        //            valid = false;
        //        }
        //    }

        //    #endregion

        //    #region Node Coloring
        //    if (!valid)
        //    {
        //        DataNode dataNode = node.Tag as DataNode;
        //        if (dataNode == null || dataNode.Deletable == false)
        //        {
        //            node.ForeColor = Color.Red;
        //        }
        //        else
        //        {
        //            node.ForeColor = Color.DarkRed;
        //        }
        //    }
        //    else
        //    {
        //        DataNode dataNode = node.Tag as DataNode;

        //        if (dataNode == null || dataNode.Deletable == false)
        //        {
        //            node.ForeColor = SystemColors.ControlText;
        //        }
        //        else
        //        {
        //            node.ForeColor = Color.DarkOrange;
        //        }
        //    }
        //    #endregion
        //    return valid;
        //}

        private void complexityCalculationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                var complexity = new DataComplexityCalculation();
                complexity.CalculateTreeNodeSize(targetTreeView);
                complexity.CalculateTreeNodeSize(sourceTreeView);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        private void resetValidationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                _projectData.GovernanceData.ResetGovernanceCheck(targetTreeView, _projectData.ProjectParameter.ProjectVersion);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
            //foreach (TreeNode child in spTreeView.Nodes)
            //{
            //    RecoloringTree(child);
            //}
        }

        private void governanceCheckToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                _projectData.GovernanceData.CheckGovernanceVoilations(targetTreeView, _projectData.ProjectParameter.ProjectVersion);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }

            //foreach (TreeNode child in spTreeView.Nodes)
            //{
            //    RecoloringTree(child);
            //}
            //var complexity = new DataComplexityCalculation();
            //complexity.CheckGovernanceRules(spTreeView, true);
        }
        #endregion

        #region Item Edit
        private void btnApproveItemChanges_Click(object sender, EventArgs e)
        {
            var node = targetTreeView.SelectedNode;

            if (node != null)
            {
                DataNode data = node.Tag as DataNode;

                //if (data.ExcludeFromMigration != cbxExcludeNodeFromMigration.Checked)
                //{
                //    data.ExcludeFromMigration = cbxExcludeNodeFromMigration.Checked;
                //    _exportHandler.ExcludeAction(node, cbxExcludeNodeFromMigration.Checked);

                //    SetExcludeFromMigrationFlagInSubTree(node, data.ExcludeFromMigration);
                //}

                if (data.Title != txtItemTitle.Text.Trim())
                {
                    //_projectData.ActionItemHandler.RenameAction(node, txtItemTitle.Text);
                    data.Title = txtItemTitle.Text.Trim();
                    node.Text = data.Title;
                }

                if (data.TargetPath != txtItemName.Text.Trim())
                {
                    //_projectData.ActionItemHandler.RenameAction(node, txtItemName.Text.Trim());
                    data.TargetPath = txtItemName.Text.Trim();
                }

                if (data.SharePointType == SharePointType.DocLibrary && data.RemoveFolderStructure != cbxRemoveFolderStructure.Checked)
                {
                    data.RemoveFolderStructure = cbxRemoveFolderStructure.Checked;
                    //_projectData.ActionItemHandler.DisableFolderStructureAction(node, cbxRemoveFolderStructure.Checked);
                    MarkFolderAsFlatten(node, cbxRemoveFolderStructure.Checked);
                }
            }
        }

        private void MarkFolderAsFlatten(TreeNode node, bool mark)
        {
            foreach (TreeNode child in node.Nodes)
            {
                DataNode dn = child.Tag as DataNode;

                if (dn.SharePointType == SharePointType.Folder)
                {
                    child.ImageIndex = child.SelectedImageIndex = mark ? 7 : 4;
                    MarkFolderAsFlatten(child, mark);
                }
            }
        }

        //private void SetExcludeFromMigrationFlagInSubTree(TreeNode node, bool excludeFromMigration)
        //{
        //    foreach (TreeNode child in node.Nodes)
        //    {
        //        DataNode dn = child.Tag as DataNode;

        //        dn.ExcludeFromMigration = excludeFromMigration;

        //        SetExcludeFromMigrationFlagInSubTree(child, excludeFromMigration);
        //    }
        //}

        private void txtItemTitle_TextChanged(object sender, EventArgs e)
        {
            TextBox tbx = sender as TextBox;
            btnApproveItemChanges.Enabled = tbx.Text.Length > 0;
        }
        #endregion

        #region REMOVE AFTER TEST
        private void exportGovernanceRulesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.RestoreDirectory = true;
            dlg.Filter = "GovernanceDefinition File|*.xml";
            dlg.Title = "Select a Governance Definition File ";

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Cursor.Current = Cursors.WaitCursor;

                try
                {
                    GovernanceHandler gv = new GovernanceHandler();
                    gv.GovernanceData = _projectData.GovernanceData;
                    gv.SaveSettings(dlg.FileName);
                }
                catch (Exception ex)
                {
                    _infoMessageHandler.PrintError(ex.Message);
                }

            }
        }

        private void exportTemplateDefinitionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.RestoreDirectory = true;
            dlg.Filter = "TemplateDefinition File|*.xml";
            dlg.Title = "Select a Template Definition File ";

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Cursor.Current = Cursors.WaitCursor;

                try
                {
                    _templateStructureLoader.SaveDefinition(dlg.FileName);
                    //TemplateDefinition.Instance.SaveDefinition(dlg.FileName);
                }
                catch (Exception ex)
                {
                    _infoMessageHandler.PrintError(ex.Message);
                }

            }

        }

        private void importGovernanceRulesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.RestoreDirectory = true;
            dlg.Filter = "Governance Definition File|*.xml";
            dlg.Title = "Governance Definition File";

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Cursor.Current = Cursors.WaitCursor;

                try
                {
                    _projectData.GovernanceData = GovernanceData.LoadXml(new FileStream(dlg.FileName, FileMode.Open));
                }
                catch (Exception ex)
                {
                    _infoMessageHandler.PrintError(ex.Message);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }

            }
        }

        private void importTemplateDefinitionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //var statistic = new MigrationStatistic();

            //statistic.MigrationPlannedSourceElements = DataComplexityCalculation.CountItemWithOutFolders(mainTree);
            //statistic.MigrationActualsSourceElements = DataComplexityCalculation.CountItemWithOutFolders(spTreeView);
            //statistic.MigrationPlannedSourceSize = DataComplexityCalculation.CountSizeWithOutFolders(mainTree);
            //statistic.MigrationActualsSourceSize = DataComplexityCalculation.CountSizeWithOutFolders(spTreeView);



            //MessageBox.Show("Currently not supported");
            //OpenFileDialog dlg = new OpenFileDialog();
            //dlg.RestoreDirectory = true;
            //dlg.Filter = "Template Definition File|*.xml";
            //dlg.Title = "Template Definition File";

            //if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    Cursor.Current = Cursors.WaitCursor;

            //    try
            //    {
            //        TemplateDefinition.Instance.ImportDefinition(dlg.FileName);
            //        CreateApplicationDynamicMenu();
            //    }
            //    catch (Exception ex)
            //    {
            //        _infoMessageHandler.PrintError(ex.Message);
            //    }
            //    finally
            //    {
            //        Cursor.Current = Cursors.Default;
            //    }

            //}
        }
        #endregion

        private void btnClearInfoMessageBox_Click(object sender, EventArgs e)
        {
            _infoMessageHandler.Clear();
        }

        private void debugInformationTreeMenuItem_Click(object sender, EventArgs e)
        {
            if (((ToolStripMenuItem)sender).Checked)
            {
                Cursor.Current = Cursors.WaitCursor;
                try
                {
                    _treeNodeDebugger.PopulateTreeIntoList(sourceTreeView, targetTreeView);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
            }
            UpdateMenuItems();
        }

        private void toolStripMenuItemOpenSpotTestDialog_Click(object sender, EventArgs e)
        {
            var dlg = new SpotTestCreation();

            dlg.ShowDialog(sourceTreeView, targetTreeView, _projectData.ProjectParameter);
            UpdateMenuItems();
        }

        //private void toolStripMenuItemActionManagement_Click(object sender, EventArgs e)
        //{
        //    var actionItemMngmt = new ActionItemManagement(_projectData.ActionItemHandler);
        //    actionItemMngmt.Show(this);
        //    UpdateMenuItems();
        //}

        private void exporterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //var dlg = new Futajma.MigrationStudio.LiveLinkExporter.Dialog.LiveLinkMappingConverter();

            //dlg.ShowDialog(_projectData.ProjectParameter, targetTreeView);

            //UpdateMenuItems();
        }

        private void aboutTheProductToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var dlg = new AboutBox();
            dlg.CenterForm(this).ShowDialog();
        }

        #region Search And Replace Characters
        //private void tryRunToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        SaveFileDialog dlg = new SaveFileDialog();
        //        dlg.RestoreDirectory = true;
        //        dlg.Filter = "Report|*.xml";
        //        dlg.Title = "Save search and replace report.";

        //        if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //        {
        //            Cursor.Current = Cursors.WaitCursor;

        //            var output = new List<SearchReplaceResult>();

        //            foreach (TreeNode childs in targetTreeView.Nodes)
        //            {
        //                _projectData.GovernanceData.SearchReplaceUnsupportedCharacters(childs, output, true);
        //            }

        //            _projectData.GovernanceData.SaveSearchReplaceUnsupportedCharacterReport(dlg.FileName, output);

        //            MessageBox.Show(string.Format("Report saved,  {0} folders and filenames replaces", output.Count), "Information: only try run!");

        //        }
        //    }
        //    finally
        //    {
        //        Cursor.Current = Cursors.Default;
        //    }
        //}

        //private void finalRunToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        SaveFileDialog dlg = new SaveFileDialog();
        //        dlg.RestoreDirectory = true;
        //        dlg.Filter = "Report|*.xml";
        //        dlg.Title = "Save search and replace report.";

        //        if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //        {
        //            targetTreeView.BeginUpdate();
        //            Cursor.Current = Cursors.WaitCursor;

        //            var output = new List<SearchReplaceResult>();

        //            foreach (TreeNode childs in targetTreeView.Nodes)
        //            {
        //                _projectData.GovernanceData.SearchReplaceUnsupportedCharacters(childs, output, false);
        //            }

        //            _projectData.GovernanceData.SaveSearchReplaceUnsupportedCharacterReport(dlg.FileName, output);

        //            MessageBox.Show(string.Format("Report saved,  {0} folders and filenames replaces", output.Count), "Information");
        //            targetTreeView.EndUpdate();
        //        }
        //    }
        //    finally
        //    {
        //        Cursor.Current = Cursors.Default;
        //    }
        //}
        #endregion

        #region Reload Governance and template definition



        private void toolStripMenuItemReloadGovernanceDefinition_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                _projectData.GovernanceData = SharePoint2010ApplicationConfiguration.LoadGovernanceData();

                if (_projectData.GovernanceData == null)
                {
                    _infoMessageHandler.PrintInfo("Governance data not loaded, use project rules");
                    _projectData.GovernanceData = new GovernanceData(true);
                }
            }
            catch (Exception ex)
            {
                _infoMessageHandler.PrintError(ex.Message);
                publishToDashboardToolStripMenuItem.Enabled = false;
                openFromDashboardToolStripMenuItem.Enabled = false;
                importFromDashboardToolStripMenuItem.Enabled = false;
                toolStripMenuItemReloadGovernanceDefinition.Enabled = false;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
        #endregion

        #region Export Violation Report
        private void tspMenuSaveViolationReport_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.RestoreDirectory = true;
                dlg.Filter = "Csv File|*.csv";
                dlg.Title = "Select report as csv File ";
                dlg.FileName = string.Format("ViolationReport_{0}", DateTime.Now.ToString("dMMyyyy_HHmmss"));

                if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Cursor.Current = Cursors.WaitCursor;
                    _projectData.GovernanceData.CheckGovernanceVoilations(targetTreeView, _projectData.ProjectParameter.ProjectVersion);
                    Cursor.Current = Cursors.Default;

                    _projectData.GovernanceData.CreateViolationExcelReport(targetTreeView, dlg.FileName);

                }
            }
            finally
            {
                Cursor.Current = Cursors.Default;
                _infoMessageHandler.PrintInfo("Violation report saved.");
            }
        }
        #endregion

        #region Load Deployment Report
        private void tspImportDeploymentReport_Click(object sender, EventArgs e)
        {
            try
            {
                //OpenFileDialog dlg = new OpenFileDialog();
                //dlg.RestoreDirectory = true;
                //dlg.Filter = "Deployment Report|*.xml";
                //dlg.Title = "Select a Tzunami Deployment Report";

                //if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                //{
                //    Cursor.Current = Cursors.WaitCursor;

                //    List<DeploymentReportImportStatus> statusList = new List<DeploymentReportImportStatus>();

                //    var importer = new DeploymentReportImporter();

                //    spTreeView.BeginUpdate();

                //    importer.ImportDeploymentReport(dlg.FileName, spTreeView, _projectData.ProjectParameter.ProjectVersion, statusList);

                //    Cursor.Current = Cursors.Default;

                //    if (MessageBox.Show("Deployment report import done. Do you want to save the logfile ? ", "Log file", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                //    {
                //        SaveFileDialog saveDlg = new SaveFileDialog();
                //        saveDlg.RestoreDirectory = true;
                //        saveDlg.Filter = "Logfile|*.txt";
                //        saveDlg.Title = "Save Log file";

                //        if (saveDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                //        {
                //            using (var sw = new StreamWriter(saveDlg.FileName, false))
                //            {
                //                foreach (var item in statusList)
                //                {
                //                    sw.Write(string.Format("{0} [{1}]{2}", item.Message, item.SourceUrl, Environment.NewLine));
                //                }
                //            }
                //            MessageBox.Show("Log file saved", "Information");
                //        }
                //    }
                //}

                Cursor.Current = Cursors.WaitCursor;
                _projectData.Importer.ImportDeploymentReport(targetTreeView, _projectData.ProjectParameter.ProjectVersion);

            }
            finally
            {
                //spTreeView.EndUpdate();
                Cursor.Current = Cursors.Default;
            }
        }
        #endregion

        #region Clean Up: the source tree if some nodes are disabled and not mapped
        private void tspCleanUpTree_Click(object sender, EventArgs e)
        {
            _treeNodeDebugger.PopulateTreeIntoList(sourceTreeView, targetTreeView);
            CleanUp.CleanUpTree(_treeNodeDebugger, sourceTreeView);

            foreach (TreeNode node in sourceTreeView.Nodes)
            {
                ItemOperation.SetItemColorForChilds(node, false, _projectData.ProjectParameter.ProjectVersion);
            }

        }
        #endregion

       

        //private void searchAndReplaceIllegalCharactersToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    _projectData.GovernanceData.ShowSearchAndReplaceDialog(targetTreeView);
        //}
    }
}